假设输入模板参数T
可能具有也可能没有内部变量bar
。我正在尝试编写一个结构,bar
当我们拥有它时返回它的值,而当我们没有它时返回一个常数。这是我的尝试:
struct A {
static constexpr unsgined int bar = 20;
hasBar = true;
};
struct B {
hasBar = false;
};
template <typename T, typename std::enable_if<T::hasBar, int>::type>
struct getBar {
static constexpr unsigned int bar = T::bar;
};
template <typename T, typename std::enable_if<!T::hasBar, int>::type>
struct getBar {
static constexpr unsigned int bar = 0;
};
int main() {
getBar<A>::bar; // Expect 20
getBar<B>::bar; //Expect 0
}
我无法使用C ++ 14编译此代码。编译器抱怨:“模板非类型参数具有不同的类型”。
为什么我们会有这样的错误,我该如何解决?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句