如何在C++中的类体之外定义一个专门的类方法?

我有一个模板类A<T>及其对整数参数的专业化。并且类及其专业化都声明了方法foo(),我想在类主体之外定义它:

#include <concepts>

template<class T> 
struct A { static void foo(); };

template<std::integral T>
struct A<T> { static void foo(); };

template<class T>
void A<T>::foo() {}

template<std::integral T>
void A<T>::foo() {}
 
int main() { A<int>::foo(); }

GCC 接受此代码。

Clang 打印错误https://gcc.godbolt.org/z/hYfYGPfMh:

error: type constraint differs in template redeclaration
template<std::integral T>

MSVC 会在两个方法定义上打印错误:

error C3855: 'A<T>': template parameter 'T' is incompatible with the declaration
error C2447: '{': missing function header (old-style formal list?)
error C2065: 'foo': undeclared identifier

请建议如何在类体之外定义方法并使所有编译器满意?

以上是如何在C++中的类体之外定义一个专门的类方法?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>