【问题标题】:How to instantiate a boost::fusion::vector member variable of a type which has no default constructor?如何实例化没有默认构造函数的类型的 boost::fusion::vector 成员变量?
【发布时间】:2012-08-14 23:32:21
【问题描述】:

我正在学习 boost::mpl 并且我有以下课程 -

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

只要我使用带有默认构造函数(或默认类型)的类型,这很好用

int main(int argc, char *argv[])
{
    typedef Demo< boost::mpl::vector< int, std::string > > D1;
    D1 d;
    D1::Dim<0>::Type &i = d.GetElement<0>();

    i = "Hello World!";

    cout << " " << i << endl;
}

但是,如果我使用没有默认构造函数的类型,则会引发编译器错误,因为向量初始化失败。有没有一种标准的方法来正确初始化成员(在构造函数中)而不诉诸指针/引用?

【问题讨论】:

    标签: c++ templates boost boost-mpl boost-fusion


    【解决方案1】:

    你可以使用fusion::vector的构造函数:

    #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/vector.hpp>
    #include <utility>
    
    struct foo {
        explicit foo(int){}
    };
    
    template< typename T > 
    class Demo
    {
    public:
        //You don't need to use variadic templates and perfect forwarding
        //but you may need to emulate them to get this effect (depending on
        //where exactly you need to construct Demo).
        //Another alternative would be to pass in a fusion::vector, and
        //copy construct `elements` with that vector.
        template<typename ...Args>
        Demo(Args&& ...args) : elements_(std::forward<Args>(args)...) {}
    
        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 boost::fusion::at_c<D>(elements_);
        }
    
    private:
        typename boost::fusion::result_of::as_vector< T >::type elements_;
    };
    
    int main() {
        Demo<boost::mpl::vector< foo, std::string > > a(foo(10),"hi");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2017-11-21
      相关资源
      最近更新 更多