C++-14 使用 enable_if_t 到 select class 的成员函数模板化在整数类型上

C++-14 using enable_if_t to select member function of class templated on integral type

我正在尝试基于一个完整的 class 模板参数启用不同的成员函数,如下所示:

#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 什么?

替换失败不是大象当它发生在模板参数推导期间

此外,enable_if_t<true>void,您不能有 void 模板非类型参数。

使用默认模板参数延迟计算:

template<int Dimension>
struct Foo
{
    template<int..., int I = Dimension, std::enable_if_t<I == 1, int> = 0>
    int bar(int i) const { return i; }
    // etc.
};

未命名参数包int... 防止试图明确指定I