Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++-14使用enable_if__t选择整型模板化类的成员函数_C++_Templates_C++14_Sfinae - Fatal编程技术网

C++-14使用enable_if__t选择整型模板化类的成员函数

C++-14使用enable_if__t选择整型模板化类的成员函数,c++,templates,c++14,sfinae,C++,Templates,C++14,Sfinae,我正在尝试基于整型类模板参数启用不同的成员函数,如下所示: #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<Dimensio

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

#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\u if\u t似乎工作正常

在这个简单的例子中,重载也可以工作,但在我的实际用例中,我需要隐藏函数,以防止意外使用和/或编译错误,具体取决于具体情况


SFINAE在这里遗漏了什么?

在模板参数推导过程中发生的替换失败并不是一个累赘

另外,如果\u t为void,并且不能有void模板非类型参数,则启用\u

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

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.
};

未命名的参数packint。。。谨防试图明确指定I.

@T.C.我强烈怀疑您的句子“替换失败不是大象”,包含错误,即使不能说它确实是错误的。很好的提示,guard pack,从未想过该技术:+1。您能举例说明此int的必要性吗?@Orient没有它,您可以编写Foo.bar0;。