你的第一個問題是:void
是一個類型,而不是一個整數。您可以使模板接受兩種類型,第二種是boost::mpl::int_
或void
。
然後你可以專門化整個結構,或者你可以把數據成員放在一個基類中並且專門化它。
#include <boost/mpl/int.hpp>
struct A {
A(int number) { /* use number */ } };
struct B { };
template <class T, class Value>
struct A_or_B_Holder_Base{
A_or_B_Holder_Base(): _t(Value::value) {}
protected:
T _t;
};
template <class T>
struct A_or_B_Holder_Base<T, void> {
A_or_B_Holder_Base(): _t() {}
protected:
T _t;
};
template <typename T, typename Value>
struct A_or_B_Holder : public A_or_B_Holder_Base<T, Value> {
};
using boost::mpl::int_;
A_or_B_Holder<A, int_<3> > x;
A_or_B_Holder<B, void> y;
A_or_B_Holder<A, void > w; //error, no default constructor
A_or_B_Holder<B, int_<3> > z; //error, no int constructor
更自然可能是不要求的參數是一個編譯時間常數(因爲你是無論如何轉動編譯時常到一個運行時間變量)。只是重載構造函數。
struct A {
A(int number) { /* use number */ } };
struct B { };
template <typename T>
struct A_or_B_Holder {
A_or_B_Holder() : _t() { }
A_or_B_Holder(int number): _t(number) {}
private:
T _t;
};
A_or_B_Holder<B> b;
A_or_B_Holder<A> a(3);
聽起來像一個升壓變體... –
正在爲A_or_B_Holder創建專門化嗎? –
專業化是不可能的 - 我必須爲類型T,T_1,T_2,...等每個私人成員創建許多專業化。我想要的是指導模板,在一種情況下,我希望T成員將被創建爲「無效」參數,而另一個成員爲「3」。 –