2012-08-24 55 views
2

我有一個類,我想從boost :: mpl :: vector中的每個類的容器繼承一個類。換句話說,這樣的事情:爲boost mpl列表中的每種類型繼承容器

template <typename types_vector> 
class A : inherit from std::vector<type> for each type in types_vector { 

}; 

舉例來說,如果我有這樣的載體:

typedef boost::mpl::vector<bool, int, double> types_vector_; 

然後A<types_vector_>將擴展爲:

class A : public std::vector<bool>, public std::vector<int>, public std::vector<double> { 

}; 

我怎麼能做到這一點不使用C++ 11功能(其餘代碼尚未準備好)?我認爲使用boost MPL是一條可行的路線,但如果除了C++ 11以外還有其他選擇,我可以考慮。

+0

唔...你可以看一下洛基... http://loki-lib.sourceforge.net/ – ForEveR

回答

3

我覺得像這樣的東西可以幫助你。

#include <boost/mpl/vector.hpp> 
#include <boost/mpl/front.hpp> 
#include <boost/mpl/pop_front.hpp> 
#include <boost/mpl/is_sequence.hpp> 
#include <boost/mpl/size.hpp> 
#include <boost/utility/enable_if.hpp> 
#include <boost/mpl/and.hpp> 
#include <boost/mpl/equal_to.hpp> 
#include <boost/mpl/greater_equal.hpp> 
#include <vector> 
#include <iostream> 

namespace mpl = boost::mpl; 

template<typename T, 
typename = void> 
struct Some 
{ 
    typedef std::vector<T> type; 
}; 

template<typename T> 
struct Some<T, 
typename boost::enable_if_c 
    < 
    mpl::and_ 
    < 
    mpl::is_sequence<T>, 
    mpl::greater_equal 
    < 
     mpl::size<T>, 
     mpl::int_<2> 
    > 
    >::type::value 
    >::type> : 
    public Some<typename mpl::front<T>::type>::type, 
    public Some<typename mpl::pop_front<T>::type> 
{ 
}; 

template<typename T> 
struct Some<T, 
typename boost::enable_if_c 
    < 
    mpl::and_ 
    < 
    mpl::is_sequence<T>, 
    mpl::equal_to 
    < 
     mpl::size<T>, 
     mpl::int_<1> 
    > 
    >::type::value 
    >::type> : 
public Some<typename mpl::front<T>::type>::type 
{ 
}; 

template<typename T> 
struct Some<T, 
typename boost::enable_if_c 
    < 
    mpl::and_ 
    < 
    mpl::is_sequence<T>, 
    mpl::equal_to 
    < 
     mpl::size<T>, 
     mpl::int_<0> 
    > 
    >::type::value 
    >::type> 
{ 
}; 


int main() 
{ 
    typedef mpl::vector<int, double> vect_t; 
    typedef Some<vect_t> vector; 
    vector vect; 
    vect.std::vector<int>::push_back(1); 
    vect.std::vector<double>::push_back(2); 
    std::cout << "int: " << vect.std::vector<int>::at(0) << std::endl; 
    std::cout << "double: " << vect.std::vector<double>::at(0) << std::endl; 
} 

http://liveworkspace.org/code/ec56ebd25b821c9c48a456477f0d42c9

相關問題