微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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++ 模板专家,我尝试过类似下面的方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。