2011-11-30 57 views
2

我正在學習Boost.MPL,我剛剛開始。所以如果解決方案是明顯的,請原諒我。我看這樣的例子:C++ Boost MPL:如何擺脫向量和callnot內部函數?

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

using namespace std; 

struct A 
{ 
    template <class T> 
    void operator()(T t) 
    { 
     cout << typeid(T).name() << "\t" << t << endl; 
    } 

    template <class TypeVector> 
    void FooAll(void) 
    { 
     boost::mpl::for_each<TypeVector>(*this); 
    } 
}; 

void main(void) 
{ 
    A a; 
    a.FooAll<boost::mpl::vector<int, float, long>>(); 
} 

,並不能幫助,但不知道如何調用FooALL(把它變成a.FooAll<int, float, long>();)時擺脫boost::mpl::vector併爲每個參數調用一些靜態/全球/或類的內部函數,而不是*this這讓我困惑?

回答

2

請看看boost tuple的實現(解決類似的問題)。主要想法是,您可以爲您的FollAll < ...>()方法指定最大數量的模板參數,併爲它們中的大多數提供默認類型。下面是我心目中

#include <boost/type_traits/is_same.hpp> 
#include <boost/mpl/eval_if.hpp> 
#include <boost/mpl/vector.hpp> 
#include <boost/mpl/push_back.hpp> 

using boost::is_same; 
using boost::mpl::eval_if; 
using boost::mpl::vector; 
using boost::mpl::push_back; 

struct EmptyType { }; 

struct A 
{ 
    template<typename arg1, typename arg2=EmptyType, typename arg3=EmptyType, ..., typename argN=EmptyType> 
    void FooAll() { 
     // reconstruct the type vector for easy manipulation later 
     // Bolierplate code! 
     typedef vector<arg> vector_arg1;  
     typedef typename eval_if<is_same<arg2, EmptyType>, 
           vector_arg1, 
           push_back<vector_arg1, arg2> >::type vector_arg2; 
     typedef typename eval_if<is_same<arg3, EmptyType>, 
           vector_arg2, 
           push_back<vector_arg2, arg3> >::type vector_arg3; 
     //... rest of arguments 
     typedef typename eval_if<is_same<argN, EmptyType>, 
           vector_arg(N-1), 
           push_back<vector_arg(N-1), argN> >::type vector_argN; 

     // now you can manipulate the reconstructed type vector 
     Do_some_internal_stuff<vector_argN>::apply(); 
    } 
} 

如果你想要去的「高科技」你可以嘗試命名Variadic Templates一個C++ 11標準功能的草圖。但請確保您所定位的編譯器已支持此功能。

最好的問候, 馬辛

+0

@ user1072853我已經更新了更多的細節的例子。我無法訪問編譯器,因此請僅將此代碼視爲草圖。 – Marcin