C++ 模板指定的类成员

C++ Class members specified by template

本文关键字:成员 C++      更新时间:2023-10-16

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

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 支持。

如果你对元组没问题,你可以定义你的结构,如下所示:

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

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

这是你想要的吗?