簡體   English   中英

如何在 C++ 中的類體之外定義一個專門的類方法?

[英]How to define a specialized class method outside of class body in 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM