[英]May I use a constant number to choose a class at compile time, possibly using templates?
假設我有一個常量值(可能是一些枚舉類型)。 假設我有很多A,B,D等課程。
我能有這樣的東西嗎?
C<1> anInstanceOfA; //This will be of type A
C<2> anInstanceOfB; //This will be of type B
C<3> anInstanceOfD; //This will be of type D
那么,是否可以在編譯時根據常數選擇一個類?
一般的問題是我試圖根據表選擇一個仿函數,其中索引是一個枚舉。 如果可能的話,我想避免多態性。
編輯:對於這個項目,我不能使用C ++ 11,無論如何,感謝誰在那個環境中回答,無論如何都知道非常有趣。
編輯2:一般來說,我可以有兩個以上的目標類,我編輯了我的問題
這不是唯一的方法,但我希望你的目的可以接受:
struct A { };
struct B { };
template <int N>
struct choices;
template <>
struct choices<1> { typedef A type; };
template <>
struct choices<2> { typedef B type; };
template <int N>
using C = typename choices<N>::type;
更新:要在沒有C ++ 11功能的情況下執行相同操作,您應該使C
類成為類型與上面相應類型別名相同的typedef
成員:
template <int N>
struct C
{
typedef typename choices<N>::type type;
};
// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
使用LSP和普通C ++ 98:
template <int N> class C;
template <> class C<1> : public A {};
template <> class C<2> : public B {};
template <> class C<3> : public D {};
C<1> anInstanceOfA;
由於C ++中的公共繼承滿足IS-A規則,因此anInstanceOfA
既是IS-A C<1>
對象又是IS_AN A
對象。
這是一個相當簡單的元函數:
template <int N>
struct C {
typedef typename std::conditional<N == 1,A,B>::type type;
};
你可以使用它作為C<1>::type foo;
。
如果您的編譯器支持C ++ 11模板別名,則可以簡化為:
template <int N>
using C = typename std::conditional<N == 1,A,B>::type;
並擁有你喜歡的C<1> foo;
句法。
在純C ++ 03中,將std::conditional
實現為:
template <bool, typename A, typename>
struct conditional {
typedef A type;
};
template <typename A, typename B>
struct conditional<false, A, B> {
typedef B type;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.