带有自定义对象的常量表达式
我正在尝试使用自定义类的实例作为模板参数。
class X {
public:
X() {};
};
template <class Foo, Foo foo>
struct Bar {
};
const X x;
Bar<X, x> foo;
编译器声明 x
不能出现在常量表达式中。为什么呢?在编译时构造该对象的一切都已给出。
I'm trying to use an instant of a custom class as a template parameter.
class X {
public:
X() {};
};
template <class Foo, Foo foo>
struct Bar {
};
const X x;
Bar<X, x> foo;
The compiler states that x
cannot appear in a constant expression. Why that? There is everything given to construct that object at compile time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你做不到。标准 14.1 说:
You can't do it. Standard 14.1 says:
正如其他人指出的那样,你做不到。只要您不玩元编程游戏,传递类的实际实例的正常方法就是在构造函数中:
As others have pointed out you can't do it. So long as you are not playing meta-programming games, the normal way to pass an actual instance of a class is in the constructor:
模板参数可以是类型或整型常量。
X
是一种类型,但x
不是。您也不能使用常量浮点值。Template parameters can be types, or integral constants.
X
is a type, butx
is not. You also can't use constant floating point values.