簡體   English   中英

使用整數常量0初始化實例,但沒有其他常量值或整數變量

[英]Initialize instance with integer constant 0 but no other constant value or integer variable

我想定義一個類,其實例可以構造,隱式構造,或者從整數常量零分配,但不能從任何其他數字常量分配,而不是從具有整數類型的變量分配(即使它的值在運行時恰好為零) )。 它也應該是同一類的其他實例的可復制構造。 只要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初始化。

你需要用常量表達式替換(v == 0)......

就像是

constexpr bool is_zero_construct(size_t number)
{
  return number == 0;
}

constexpr X(int v) { static_assert(is_zero_construct(v), "must be initialized from zero"); }

您可以利用只有0可以隱式轉換為指針的事實:

struct X {
  X();
  X(void*);
};

這滿足了您的要求,但當然也允許使用指針進行初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM