[英]Using constexpr when a value is non-const but initialized with a constant expression?
[英]Using non-const variable inside constexpr?
因此,對於先前關於使用三元運算符const / non-const的問題,關於C ++ 11標准的以下test
函數是否可以:
template<bool UseConst> class MyClass
{
public:
constexpr bool test()
{
return (UseConst) ? (_constvar) : (_var);
}
protected:
int _var;
static const int _constvar;
}
整個問題是_constvar
是const,而_var
是非const。 我將必須通過相同的函數根據模板參數訪問這2個數據,並且當我使用const時,我希望有一個編譯時函數。
test()
函數滿足我的要求嗎?
您可以使用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
,如果UseConst
為false
, test
將降級為運行時函數,但是當UseConst
為true
,您將獲得一個編譯時函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.