2017-10-27 9 views
1

ここにいくつかの答えがあります(How to loop through a boost::mpl::list?は私が始めたものです)は、boost :: mplにフィードする汎用ラムダを構築できるはずです: :for_each()しかし、私は実際の例を見つけることができないか、自分自身を構築することができません。私はラムダに行うことができるようにしたいものをboost :: mpl :: for_each()でジェネリックラムダを呼び出す

Idealyは、私は現在、

for(int k = 0; k < 2; ++k) 
{ 
    TestFunction<int>(k); 
    TestFunction<long>(k); 
    TestFunction<float>(k); 
    TestFunction<double>(k); 
}; 

と交換するようなものでループで呼んでいる

template<typename T> 
void TestFunction(const int &p) 
{ 
    T t(p); 
    std::cout << "p = " << p << ", t = " << t << std::endl; 
}; 

のような関数を取ることです

typedef boost::mpl::list<int, long, float, double> ValidTypes; 

for(int k = 0; k < 2; ++k) 
{ 
    // lambda definition that captures k 

    // boost::mpl::for_each(ValidTypes, ...) that calls the lambda. 
}; 

これは可能ですか?他のmpl構造のいずれかとfor_each()を使用しない場合は?私は演算子()をオーバーロードするコードを実行していますが、可能であればラムダ・ソリューションを見たいと思います。

ありがとう、 アンディ。

答えて

0

あなたがC++ 14の一般化ラムダを使用することができる場合、あなたはpの値をキャプチャしても、現在の有効なタイプのタイプはラムダに渡される推論することができます

#include <boost/mpl/for_each.hpp> 
#include <boost/mpl/list.hpp> 
#include <iostream> 

int main() 
{ 
    using ValidTypes = boost::mpl::list<int, long, float, double>; 

    for (auto k = 0; k < 2; ++k) { 
     boost::mpl::for_each<ValidTypes>([p = k](auto arg) { 
      using T = decltype(arg); 
      T t(p); 
      std::cout << "p = " << p << ", t = " << t << '\n'; 
     }); 
    } 
} 

Live Example

編集:余分な信用のために、ここにもデフォルト以外の構成可能なタイプのために働く、もう少し高度なバージョンがあります:

#include <boost/mpl/for_each.hpp> 
#include <boost/mpl/list.hpp> 
#include <iostream> 

class NonDefaultConstructible 
{ 
    int value; 
public: 
    NonDefaultConstructible(int const& p) : value(p) {} 

    friend auto& operator<<(std::ostream& ostr, NonDefaultConstructible const& ndc) 
    { 
     return ostr << ndc.value; 
    } 
}; 

int main() 
{ 
    using ValidTypes = boost::mpl::list<int, long, float, double, NonDefaultConstructible>; 

    for (auto k = 0; k < 2; ++k) { 
     boost::mpl::for_each<ValidTypes, boost::mpl::make_identity<boost::mpl::_1>>([p = k](auto arg) { 
      using T = typename decltype(arg)::type; 
      T t(p); 
      std::cout << "p = " << p << ", t = " << t << '\n'; 
     }); 
    } 
} 

Live Example

make_identityの幾分畳み込まれた使用の説明については、私のvery first Q&Aをここに見てください!

+0

ありがとうございます@TemplateRex! make_identity <>トリックは、私の試みからの欠けているリンクでした! – Andy

関連する問題