gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:12:19 25 4
gpt4 key购买 nike

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
铛:

error: out-of-line definition of 'test' does not match any declaration in 'test<true>'


msvc:

error C2244: 'test<true>::test': unable to match function definition to an existing declaration

最佳答案

您正在声明受约束的构造函数,但定义了两个不受约束的特化。那些永远不会匹配。
你的意思可能是:

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 (强调我的):

When a member of a class template is defined outside of the class template definition, the member definition is defined as a template definition with the template-head equivalent to that of the class template.


[temp.over.link]/6 :

Two template-heads are equivalent if their template-parameter-lists have the same length, corresponding template-parameters are equivalent and are both declared with type-constraints that are equivalent if either template-parameter is declared with a type-constraint, and if either template-head has a requires-clause, they both have requires-clauses and the corresponding constraint-expressions are equivalent.


另见 [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>

关于c++ - 引导构造函数的外定义(c++20),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66904905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com