问题描述
我有一个模板类 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>
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++ 模板专家,我尝试过类似下面的方法
template<class T,bool = std::is_integral_v<T>>
struct A
{};
template<class T>
struct A<T,false>
{
static void foo();
};
template<class T>
struct A<T,true>
{
static void foo();
};
template<class T>
void A<T,false>::foo()
{
std::cout << "I am working on a non-integral type" << std::endl;
}
template<class T>
void A<T,true>::foo()
{
std::cout << "I am working on an integral type" << std::endl;
}
int main()
{
A<int>::foo();
A<float> ::foo();
return 0;
}
代码给了我 MS C++ 编译器的结果
I am working on an integral type
I am working on a non-integral type