gpt4 book ai didi

c++ - 包含依赖于类成员的模板的类

转载 作者:行者123 更新时间:2023-11-28 07:36:42 26 4
gpt4 key购买 nike

目标是制作一种“智能 getter ”,如果当前对象存在则从中获取值,如果不存在,则在父对象中查找值。

所以这个 ValueGetter 类包含指向它所包含的对象的指针(在构造函数中将其作为运行时参数获取)和指向它作为模板参数运行的成员的指针。

这是最简单的例子:

template <class StyleType, int StyleType::*value>
struct ValueGetter
{
ValueGetter(StyleType* containedIn);
int get();
// Looks if the value is present in this style,
// if not it looks for the value in the parent style
};

struct Style
{
Style *parent;
int a;
ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator
};

当我将 x 移出类的范围时,它会编译。通常类可以​​包含依赖于类类型的模板,那么为什么这不起作用呢?有没有其他方法可以解决这个问题而不在构造函数的运行时存储指向成员的指针? (因此该结构将为每个值包含额外的指针)

编辑:我刚刚在 GCC 中成功编译了它,但在 MSVC (2012) 中却没有,所以这是 MSVC 编译器错误吗?

最佳答案

我认为在 03 C++ 中不允许将指针(不要与 T* 中的指针类型混淆)作为模板参数,仅允许类型名称、整型常量或枚举常量。甚至没有 float/double 常量。这包括类成员指针。

更新:此外,静态非类型参数有效:

template <class StyleType, int *value>
struct ValueGetter
{
ValueGetter(StyleType* containedIn);
int get();
// Looks if the value is present in this style,
// if not it looks for the value in the parent style
};

struct Style
{
Style *parent;
static int a;
ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator
};

关于c++ - 包含依赖于类成员的模板的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16654116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com