我有一個模板類,我想為其提供一個 constexpr 整數,其值由模板引數中是否存在 constexpr 整數確定:
template<typename Traits>
class Foo
{
static constexpr int MaxDegree =
std::conditional<
std::is_integral<Traits::MaxDegree>::value,
std::integral_constant<int, Traits::MaxDegree>,
std::integral_constant<int, 0>
>::value;
};
struct TraitA { };
struct TraitB { constexpr static int MaxDegree = 1; };
int main()
{
std::cout
<< Foo<TraitA>::MaxDegree /* should be 0 */ << " "
<< Foo<TraitB>::MaxDegree; /* should be TraitB::MaxDegree == 1 */
<< "\n";
}
顯然,這不起作用,因為std::is_integral
TraitA 失敗了。有什么可行的嗎?
我受限于 c 11。
uj5u.com熱心網友回復:
Traits::MaxDegree
如果成員不存在,則會產生編譯器錯誤。這意味著您不能直接將此代碼用作運算式的一部分。
不過,您可以將 constexpr 函式與 SFINAE 一起使用來實作這一點:
template<class T>
constexpr typename std::enable_if<std::is_integral<decltype(T::MaxDegree)>::value, int>::type GetMaxDegree()
{
return T::MaxDegree;
}
template<class T>
constexpr int GetMaxDegree(...) // this one is only used, if the first version results in a substitution failure
{
return 0;
}
template<typename Traits>
class Foo
{
public:
static constexpr int MaxDegree = GetMaxDegree<Traits>();
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/469962.html