2012-11-27 3 views
6

Augenblick zurückkehren, ich habe folgendes gelten zwei Funktionen auf einen Wert und gibt eine 2-Werttupel:ein Tupel von Funktionen auf einen Wert Nehmen und ein Tupel

template<typename F1, typename F2> 
class Apply2 
{ 
public: 
    using return_type = std::tuple<typename F1::return_type, typename F2::return_type>; 

    Apply2(const F1& f1, const F2& f2) : f1_(f1), f2_(f2) {} 

    template<typename T> return_type operator()(const T& t) const 
    { 
     return std::make_tuple(f1_(t), f2_(t)); 
    } 

protected: 
    const F1& f1_; 
    const F2& f2_; 
}; 

ich dies verallgemeinern wollte N Funktionen:

template<typename ...F> 
class ApplyN 
{ 
public: 
    using return_type = std::tuple<typename F::return_type...>; 

    ApplyN(const std::tuple<F...>& fs) : functions_(fs) {} 

    template<typename T> return_type operator()(const T& t) const 
    { 
     return ???; 
    } 

protected: 
    std::tuple<F...> functions_; 
}; 

ich weiß, dass ich wohl irgendwie Vorlage Rekursion verwenden müssen, aber ich kann meinen Kopf um es nicht wickeln. Irgendwelche Ideen?

+3

Noch ein Job für Superman! Ähm, ich meine, für [Indizes] (http://stackoverflow.com/a/10930078/46642). –

Antwort

4

Es dauerte eine Weile, aber hier ist es (mit indices):

template<typename ...F> 
class ApplyN 
{ 
public: 
    using return_type = std::tuple<typename F::return_type...>; 

    ApplyN(const F&... fs) : functions_{fs...} {} 

    template<typename T> return_type operator()(const T& t) const 
    { 
     return with_indices(t, IndicesFor<std::tuple<F...> >{}); 
    } 

protected: 
    std::tuple<F...> functions_; 

    template <typename T, std::size_t... Indices> 
    return_type with_indices(const T& t, indices<Indices...>) const 
    { 
     return return_type{std::get<Indices>(functions_)(t)...}; 
    } 
}; 

Jemand, bevor Sie eine (unvollständige) Antwort hatte, aber er/sie gelöscht - das war mein Ausgangspunkt. Wie auch immer, danke, Fremder! Danke R. Martinho Fernandes auch!

+1

Gut gemacht! Ich habe vorher keine Antwort gepostet, weil ich auf der Arbeit war, also habe ich den Kommentar hinterlassen, so dass jemand von dort abholen würde. Ich bin froh, dass es genug war, um * Sie * zu einer Lösung zu bringen. –