【问题标题】:Defining member variables from a boost::mpl:vector typelist从 boost::mpl:vector 类型列表定义成员变量
【发布时间】:2012-08-14 11:03:37
【问题描述】:

我是 boost::mpl 和 TMP 的新手。我正在尝试按如下方式构建一个类-

template< typename T > 
class Demo
{
public:
    typedef boost::mpl::size<T> NumDimensions;

    template< size_t D >
    struct Dim
    {
        typedef typename boost::mpl::at_c< T, D >::type Type;
    };

    //I want to implement this function
    template< size_t D >
    typename Dim<D>::Type GetElement() 
    {
        if(D == 0)
        {
            return element1_;
        }
        if(D == 1)
        {
            return element2_;
        }
        ....
    }

private:
    typename Dim<0>::Type element1_;
    typename Dim<1>::Type element2_;
    ....
};

我打算按如下方式使用这个类-

typedef Demo< boost::mpl::vector< int, float, long > > D1;
D1 d;
D1::Dim<0>::Type i = d.GetElement<0>();

我很想知道是否有更好的方法来声明这些元素,而不是硬编码和重复它们的声明(和返回) - 一些(可能)类似于具有异构类型和更简单访问元素的数组。

注意:- 此代码可能有编译器错误(我没有测试过),但我希望它传达了我的问题。

【问题讨论】:

  • 事实上,你想要的是一个tuple,无论是来自Boost 还是C++11 标准。您可能手动执行的所有操作都会重新实现。

标签: c++ templates boost-mpl tmp


【解决方案1】:

您应该找到一种从类型列表中创建元组的方法。 这是一篇文章,似乎描述了如何使用 C++11 功能完成此操作。 http://www.devx.com/cplus/Article/41533/1954 还有一个 talk Stephen Lavavej 在“Going Native 2012”中。

【讨论】:

  • 虽然这没有提供完整的答案,但它引导我使用 Boost.Fusion。请参阅下面的答案以获取有效的解决方案。
【解决方案2】:

我最终使用 boost::fusion::vector 如下 -

#include <iostream>
#include <tuple>
#include <string>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/at.hpp>

#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/container.hpp>


using namespace boost;
using namespace std;

template< typename T > 
class Demo
{
public:
    typedef boost::mpl::size<T> NumDimensions;

    template< size_t D >
    struct Dim
    {
        typedef typename boost::mpl::at_c< T, D >::type Type;
    };

    template< size_t D >
    typename Dim<D>::Type& GetElement()
    {
        return fusion::at_c<D>(elements_);
    }

private:
    typename fusion::result_of::as_vector< T >::type elements_;
};

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多