【发布时间】:2019-04-23 01:58:41
【问题描述】:
假设输入模板参数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 编译此代码。编译器报错:“模板非类型参数有不同的类型”。
为什么会出现这样的错误,我该如何解决?
【问题讨论】:
-
谢谢@Barry。我修改了代码以增强完整性。
标签: c++ templates c++14 template-meta-programming sfinae