在C++ 11中,我希望只有在默認模板值被選中的情況下,才能在類和構造函數中使用其成員變量(僅適用於支持的類型,如int , 當然)。成員變量和構造函數依賴於模板參數
什麼是推薦的方法來實現這一點(允許提升)?
喜歡的東西:
template< int _x = -1 > struct C {
C() {} // only available if _x != -1
C(int x) : x(x) {} // only available if _x == -1
// more methods that are common for all _x and refer to _x/x
private:
int x; // only available if _x == -1
// more members that are common for all _x
};
或者,以另一種方式:對於規模和速度優化,我想用一個編譯時間常數代替如果存儲在一個成員變量的值大於另一個值模板默認被選中。
-
這裏是做出了榜樣一切更加清晰:
template< int _size = -1 > struct Block {
Block() { buf = mmap(_size, ...); } // exists only when size!=-1
Block(int s) { buf = mmap(size = s, ...); } // exists only when size==-1
~Block() { munmap(buf, getSize()); } // should use the correct size
int getSize() const { return ???; } // gets _size if !=-1, size otherwise
// other methods that use buf and getSize()
private:
void *buf;
const int size; // only exists for size == -1!
};
這解決了它部分:
template< int _x > struct X {
int getX() const { return _x; }
};
template<> struct X< -1 > {
X(x) : x(x) {}
int getX() const { return _x; }
private:
int x;
};
template< int _x = -1 > struct C : X<_x> {
C() {} // only available if _x != -1
C(int x) : X<_x>(x) {} // only available if _x == -1
// more methods that are common for all _x and use this->getX()
};
但是,我們的C
的構造,以及其他的/更好的解決方案?
哦,那個'使用'技巧可能真的做到了,謝謝!有沒有其他的選擇,例如,如果我不僅有一個參數像'_x',而是'_x'和'_y'? – Thomas 2013-04-08 19:17:22
@Thomas對'B'有三個專業?我知道,這並不是真正的擴展,但它取決於你的用例的很多細節......恐怕沒有我知道的簡單而通用的解決方案。 – 2013-04-08 19:22:55
@Thomas我已將我的例子顛倒過來,請參閱經過編輯的答案! – 2013-04-08 19:28:16