引导构造函数的外行定义 (c++20)

问题描述

g++ 欣然接受以下代码,而 clang 和 msvc 都能够匹配行外定义。

知道为什么吗?

template <bool B>
struct test 
{
    test() requires (B);
    test() requires(!B);
};


template <>
test<true>::test()
{}

template <>
test<false>::test()
{}

int main()
{
    test<false> a;
    test<true> b;
    return 0;
}

Demo

铿锵:

错误:“test”的外部定义与“test<true>”中的任何声明都不匹配

微信:

错误 C2244:“test<true>::test”:无法将函数定义与现有声明相匹配

解决方法

您声明了受约束的构造函数,但定义了两个不受约束的特化。那些永远不会匹配。

你可能的意思是:

template <bool B>
struct test
{
    test() requires (B);
    test() requires(!B);
};

template <bool B>
test<B>::test() requires (B)
{}

template <bool B>
test<B>::test() requires (!B)
{}

这在所有 3 个编译器中都可以正常编译。

至于为什么你的原始版本编译 - 这是一个 GCC 错误 96830。 Clang 是对的,代码格式错误,因为外部定义与模板定义不匹配(还要注意 template<> ...完全专业化语法)。

参见[temp.class.general]/3(强调我的):

当类模板的成员在类模板定义之外定义时,成员定义被定义为具有template-head 等价物的模板定义> 到类模板的那个。

[temp.over.link]/6

两个模板头等价,如果它们的模板参数列表具有相同的长度,对应template-parameters 是等效的,并且都用 type-constraints 声明,如果任一 template-parameter 声明为 type,则它们是等效的-constraint,并且如果任一template-head 有一个 requires-clause,那么它们都有 requires-clause,并且相应的约束表达式是等价的 .

另请参阅 [temp.mem.func]/1 以了解在外声明受约束成员的示例:

template<typename T> struct S {
    void f() requires C<T>;
    void g() requires C<T>;
};

template<typename T>
void S<T>::f() requires C<T> { }      // OK
template<typename T>
void S<T>::g() { }                    // error: no matching function in S<T>