C++ 模板指定的类成员
C++ Class members specified by template
是否可以使用可变参数模板来指定类的成员?可接受的解决方案涉及将数据内部存储在元组中。
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
这是你想要的吗?
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗