2012-11-27 45 views
6

,我有以下的申請兩個函數的值,並返回一個2值元組:應用功能的元組的值,現在返回一個元組

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_; 
}; 

我想概括這N函數:

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_; 
}; 

我知道我可能需要使用模板遞歸莫名其妙,但我不能包裹我的頭。有任何想法嗎?

+3

超人又一份工作!嗯,我的意思是,[索引](http://stackoverflow.com/a/10930078/46642)。 –

回答

4

我花了一段時間,但在這裏它是(使用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)...}; 
    } 
}; 

有人之前有一個(不完全)的答案,但他/她抹去它 - 這是我的起點。無論如何,謝謝陌生人!謝謝R.馬丁霍費爾南德斯!

+1

幹得好!我之前沒有發佈答案,因爲我在工作,所以我留下了評論,所以有人會從那裏拿起。我很高興這足以讓你獲得解決方案。 –