【发布时间】:2016-04-27 23:00:04
【问题描述】:
我正在尝试基于一个完整的类模板参数启用不同的成员函数,如下所示:
#include <type_traits>
template<int Dimension>
struct Foo
{
template<std::enable_if_t<Dimension == 1> = 0>
int bar(int i) const { return i; }
template<std::enable_if_t<Dimension == 2> = 0>
int bar(int i, int j) const { return i + j; }
};
int main(int argc, const char **argv)
{
Foo<1> a;
a.bar(1);
Foo<2> b;
b.bar(1,2);
return 0;
}
在c++-14模式下使用gcc5编译失败,报以下错误:
tools/t1.cpp: In instantiation of 'struct Foo<1>':
tools/t1.cpp:18:12: required from here
tools/t1.cpp:13:9: error: no type named 'type' in 'struct std::enable_if<false, int>'
int bar(int i, int j) const { return i + j; }
^
tools/t1.cpp: In instantiation of 'struct Foo<2>':
tools/t1.cpp:21:12: required from here
tools/t1.cpp:10:9: error: no type named 'type' in 'struct std::enable_if<false, int>'
int bar(int i) const { return i; }
这些似乎表明 SFINAE 没有达到我的预期,因为 enable_if_t 似乎工作正常。
在这个简单的例子中,重载也可以,但在我的实际用例中,我需要隐藏函数以防止意外使用和/或编译错误,具体取决于具体情况。
我在这里缺少 SFINAE 什么?
【问题讨论】:
标签: c++ templates c++14 sfinae