模板类带有模板成员
template class to class with template member
本文关键字:成员 更新时间:2023-10-16
类似这样的类模板
template <typename... T>
class Action {
private:
std::tuple<T...> m_args;
public:
Action(T... args) : m_args(args...) {}
}
带有模板成员的课程。之所
class Action {
private:
// this does not work, how to declare the tuple type so that It can hold any arguments list.
template <typename... T>
std::tuple<T...> m_args;
public:
template <typename... T>
Action(T... args) : m_args(args...) {}
}
将您的思想放在编译器的角度上。如果该尺寸取决于解决哪个构造函数,我们值得信赖的朋友如何知道Action
需要多少存储空间?这是不可能的。
template<typename... T>
Action(T... args) : m_args(args...) {}
// wait what???
Action(int someArg) : m_args(someArg) {}
假设第二个构造函数是有效的,或者我们有两个Action
对象,其中包含不同的参数传递到构造函数 - sizeof(Action)
应该是什么?
如果您陷入了这样的问题,请将其作为编译器:可能有些人不得不给出足够的理由为什么不应该支持它,仅仅是因为它只会使实施变得复杂并具有绩效含义。
由于您提到了使用指针而不是聚合对象,所以我想我会向您展示如何进行完整性。请注意,这具有性能含义,因为您现在正在为堆上的m_args
分配内存,而不是堆栈。
class Action
{
public:
template<typename... T>
using TArgs = std::tuple<T...>;
std::shared_ptr<void> m_args;
template<typename... T>
Action(T... args)
: m_args(std::make_shared<TArgs<T...>>(args...)) {}
};
Action myAction(1, 2.0, 3.5f);
auto *myActionArgs =
static_cast<Action::TArgs<int, double, float>*>(myAction.m_args.get());
// 2.0
double secondArg = std::get<1>(*myActionArgs);
这看起来并不有趣。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗