我想定义一个类,它的实例可以从整数常量零构造、隐式构造或赋值,但不能从任何其他数字常量,也不能从整数类型的变量(即使它的值恰好是运行时为零)。它也应该可以从同一类的其他实例复制构造。只要 g++ 4.6 和 MSVC 2010 都支持(在适当的模式下),就可以使用 C++11 功能。
具体地,给定
class X { /* ... */ };
void fn(X);
这些都应该编译:
X a(0);
X b = 0;
X c; c = 0;
X d = a;
X e; e = a;
fn(0);
但这些不应该:
X f(1);
X g = 1;
X h; h = 1;
fn(1);
int ii = 23;
X a(ii);
X j = ii;
X k; k = ii;
fn(ii);
我试过了,但是没用:
class X {
public:
X() {}
constexpr X(int v) { static_assert(v == 0, "must be initialized from zero"); }
};
⟶
test.cc: In constructor ‘constexpr X::X(int)’:
test.cc:3:29: error: non-constant condition for static assertion
test.cc:3:29: error: ‘v’ is not a constant expression
最佳答案
如果需要 C++0x,您可以使用 std::nullptr_t
:
class X
{
public:
X () { }
X (std::nullptr_t) { }
void operator= (std::nullptr_t) { }
};
当然,缺点是 X
也可以用 nullptr
初始化。
关于c++ - 使用整数常量 0 初始化实例,但没有其他常量值或整数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691268/