模板指定的C ++类成员

时间:2019-02-12 07:23:42

标签: c++

是否可以使用可变参数模板指定类的成员?可接受的解决方案将涉及在内部将数据存储在元组中。

template <typename ... Args> 
struct FromPP {
     // TODO: Get the tuple type from parameter pack
     std::tuple<> data;    
     // TODO: write the constructors

     // Other code... E.g. A print method, and manipulations with 
     // other points of the same type... 
}

理想情况下,我希望某些实现既具有默认构造函数又具有复制构造函数的实现:

FromPP<float>();    // decltype(data) == std::tuple<float>
FromPP<float>(1.1); // decltype(data) == std::tuple<float>

FromPP<float,int>();       // decltype(data) == std::tuple<float,int>
FromPP<float,int>(1.1, 5); // decltype(data) == std::tuple<float,int>

如果可能的话,我想要一个C ++ 11解决方案。我们使用的某些硬件支持C ++ 14。

1 个答案:

答案 0 :(得分:3)

如果对元组没问题,可以按以下方式定义结构:

template <typename... Args> 
struct FromPP {
   std::tuple<Args...> data;    

   FromPP() = default;
   FromPP(Args&&... args) : data(std::forward<Args>(args)...) { }
};

它适用于您的示例代码:https://wandbox.org/permlink/163TwS1SrKULgfIH

是您想要的吗?

相关问题