2012-09-26 46 views
2

因此至約常量/非const與三元運算前一個問題,是以下test函數確定關於到C++ 11標準:內用constexpr非const變量?

template<bool UseConst> class MyClass 
{ 
    public: 
     constexpr bool test() 
     { 
      return (UseConst) ? (_constvar) : (_var); 
     } 

    protected: 
     int _var; 
     static const int _constvar; 
} 

整個問題是,_constvar是常量,並且_var是非常量。我會通過同樣的功能來訪問這些數據2取決於模板參數,我想有一個編譯時功能,當我使用常量。

執行test()功能滿足我的要求嗎?

+0

爲什麼就不能專注於'UseConst'從那裏走? – Xeo

+0

專營什麼?類或函數?對於這個類,我有一大組函數,並且通過像這裏這樣的單個函數來獲取const或non-const會更加簡單和簡潔。爲了專門化這個功能,我沒有看到怎麼做...... – Vincent

+0

@Vincent:類模板裏面的非模板成員函數實際上只是函數模板,並且可以專門化,而不需要專門化整個類。見例如在[這個答案]中的代碼(http://stackoverflow.com/a/12598245/636019)。 – ildjarn

回答

0

你可以使用SFINAE以「專注」你test功能。換句話說,你可以做類似如下:

template<bool true_false> 
struct true_type 
{ 
    static char value; 
}; 

template<> 
struct true_type<false> 
{ 
    static char value[2]; 
}; 

template<bool UseConst> class MyClass 
{ 
    private: 
     constexpr int pre_test(const char arg) { return _constvar; } 
     int pre_test(char (&)[2]) const { return _var; } 

    public: 
     constexpr int test() 
     { 
      return pre_test(true_type<UseConst>::value); 
     } 

    protected: 
     int _var; 
     static const int _constvar; 
}; 

現在,當你調用MyClass::test,如果UseConstfalsetest會降低到一個運行時功能,但是當UseConsttrue,你會得到一個編譯時函數。