[英]How to define a specialized class method outside of class body in C++?
I have a template class A<T>
and its specialization for integral arguments.我有一个模板类A<T>
及其对整数参数的专业化。 And both the class and its specialization declare the method foo()
, which I would like to define outside of class bodies:并且类及其特化都声明了方法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 accepts this code. GCC 接受此代码。
Clang prints the error https://gcc.godbolt.org/z/hYfYGPfMh : Clang 打印错误https://gcc.godbolt.org/z/hYfYGPfMh :
error: type constraint differs in template redeclaration
template<std::integral T>
And MSVC prints errors on both method definitions: 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
Please suggest how to define methods outside class bodies and make all the compilers happy?请建议如何在类体之外定义方法并使所有编译器满意?
I am not a C++ template expert, I tried something like below我不是 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;
}
and the code gave me the results on MS C++ compiler代码给了我 MS C++ 编译器的结果
I am working on an integral type
I am working on a non-integral type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.