我想定义一个类,其实例可以构造,隐式构造,或者从整数常量零分配,但不能从任何其他数字常量分配,而不是从具有整数类型的变量分配(即使它的值在运行时恰好为零) ).它也应该是同一类的其他实例的可复制构造.只要g ++ 4.6和MSVC 2010支持(在适当的模式下),就可以使用C++ 11功能.
具体地说,给定
class X { /* ... */ };
void fn(X);
Run Code Online (Sandbox Code Playgroud)
这些都应该编译:
X a(0);
X b = 0;
X c; c = 0;
X d = a;
X e; e = a;
fn(0);
Run Code Online (Sandbox Code Playgroud)
但这些不应该:
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);
Run Code Online (Sandbox Code Playgroud)
我试过这个,但它不起作用:
class X {
public:
X() {}
constexpr X(int v) { static_assert(v == 0, "must be initialized from zero"); }
};
Run Code Online (Sandbox Code Playgroud)
⟶
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
Run Code Online (Sandbox Code Playgroud)
小智 2
如果需要 C++0x,您可以使用std::nullptr_t:
class X
{
public:
X () { }
X (std::nullptr_t) { }
void operator= (std::nullptr_t) { }
};
Run Code Online (Sandbox Code Playgroud)
好吧,当然,也X有可以初始化的缺点。nullptr
| 归档时间: |
|
| 查看次数: |
277 次 |
| 最近记录: |