在模板参数中是否禁止 SFINAE,还是我遇到了叮当错误



以下是我用真实代码遇到的问题的简化版本。

短版本:只需查看代码和错误 gcc.godbolt.org/长版本:继续阅读;)

假设我想要一个带有模板参数setting和方法int func(int)的类,例如:

  • setting false时,func返回其参数
  • settingtrue时,func加倍其参数

最简单的方法是专用化类模板:

template<bool setting> struct A {
    int func(x) const { return 2 * x; }
};
template<> struct A<false> {
    int func(x) { return x; }
};

这种方法的问题在于,如果我有一堆不依赖于setting的其他方法,我将不得不将它们复制粘贴到两个专用化中(或者从公共基础继承,当没有太多的相互依赖时)。

因此,我可以使用 SFINAE 来选择正确的方法,例如使用 std::enable_if .这要求方法具有模板参数,因为替换失败必须仅使方法无效,而不是使整个类无效。据我所知,故障可能发生在以下任一方面:

  • 方法的参数类型
  • 方法的返回类型
  • 模板参数类型

下面是使用该方法参数的代码:

template<bool setting> struct B {
    template<bool when=true>
    int func(int x
            , typename std::enable_if<when && setting>::type * u=0
            )
    { return 2 * x; }
    template<bool when=true>
    int func(int x
            , typename std::enable_if<when && !setting>::type * u=0
            )
    { return x; }
};

下面是使用该方法的模板参数的版本:

template<bool setting> struct C {
    template<bool when=true, typename std::enable_if<
              when && setting
            >::type...>
    int func(int x) { return 2 * x; }
    template<bool when=true, typename std::enable_if<
              when && !setting
            >::type...>
    int func(int x) { return x; }
};

我倾向于使用最后一个版本,因为它使该方法的签名更具可读性,但这是个人品味的问题。

我的问题与最后一个版本有关:它是否有效C++? gcc 编译得很好,但 clang 没有(用 -std=c++11/c++1y/c++1z 测试,结果相同)。类定义本身编译正常,但在实例化时会发生错误:

int main() {
    A<true> a;
    B<true> b;
    C<true> c;
    return a.func(1) + b.func(2) + c.func(3);
}

在 gcc 5.3 中编译,但不使用 clang 3.7.1 编译:

test.cpp:30:36: error: call to member function 'func' is ambiguous
                return a.func(1) + b.func(2) + c.func(3);
                                            ~~^~~~
test.cpp:20:7: note: candidate function [with when = true, $1 = <>]
                int func(int x) { return 2 * x; }
                    ^
test.cpp:23:7: note: candidate function [with when = true, $1 = <>]
                int func(int x) { return x; }
                    ^
1 error generated.

那么这个C++有效吗?这是一个叮当错误还是 gcc 接受此代码是错误的?

模板参数中是否禁止 SFINAE

它是有效的。例如,您可以执行以下操作:

template<bool setting> struct C {
    template<bool when=true, typename std::enable_if<
              when && setting
            >::type* = nullptr>
    int func(int x) { return 2 * x; }
    template<bool when=true, typename std::enable_if<
              when && !setting
            >::type* = nullptr>
    int func(int x) { return x; }
};

演示

typename std::enable_if<when && !setting>::type...的问题应该与CWG 1558有关。
因此,您的代码在 C++17 中应该是正确的。

最新更新