【问题标题】:C++-14 using enable_if_t to select member function of class templated on integral typeC++-14 使用 enable_if_t 选择以整数类型为模板的类的成员函数
【发布时间】: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


    【解决方案1】:

    在模板参数推导过程中发生替换失败并不是一件容易的事

    另外,enable_if_t&lt;true&gt;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.
    };
    

    未命名的参数 packint... 防止尝试显式指定 I

    【讨论】:

    • @T.C.我强烈怀疑您的句子 Substitution failure is not an evil 包含错误(即使不能说它确实是错误的)。
    • 很好的提示保护包,从来没想过这种技术:+1
    • 你能举例说明这个int...的必要性吗?
    • @Orient 没有它,你可以写Foo&lt;2&gt;().bar&lt;1&gt;(0);
    猜你喜欢
    • 2017-11-03
    • 2011-07-06
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2018-01-28
    相关资源
    最近更新 更多