.cpp和.h文件中的模板专用化声明

Template specialization declaration in .cpp and .h files

本文关键字:专用 声明 文件 cpp      更新时间:2023-10-16

我想在.cpp文件中定义我的模板专用化,而不是在.h文件中。有什么办法我能做到这一点吗?我正在使用g++编译器

//main.cpp
#include <iostream>
#include <string>
#include "People.cpp"
using  namespace std;
int main() {

Spunky <int> obj3(1);
Spunky<char>obj2('y');
return 0;
}
//People.cpp
#include <iostream>
#include "People.h"

using namespace std;
// TEMPLATE SPECIALISATION
template < class T>
Spunky <T>:: Spunky( T x){
cout << x << " is not a character ! " << endl;
}
template <>
Spunky:: Spunky<char> ( char x ) {
cout << x << " is indeed a character"<< endl;
}

//People.h
#ifndef PEOPLE_H
#define PEOPLE_H
using namespace std;
// TEMPLATE SPECIALISATIONS
template < class T>
class Spunky{
public:
Spunky ( T x) ;
};
template <>
class Spunky <char> {
public:
Spunky (char x);
//  {  cout<< x << "is indeed a character"<<endl; }
};
#endif

编译器错误为:

template argument deduction is only available with -stdC==1z or -std=gnu++1z

我该怎么着手解决这个问题?

template <>
Spunky:: Spunky<char> ( char x ) {
cout << x << " is indeed a character"<< endl;
}

不是用于定义成员方法实现的正确语法。Spunky:: Spunky<char>是用于定义方法的语法,该方法本身是模板化的,而不是模板化的类,正确的语法是Spunky<char>::Spunky

在定义模板成员专业化时,也没有指定template <>

因此,完整的定义应该是:

inline Spunky<char>::Spunky( char x ) {
cout << x << " is indeed a character"<< endl;
}

我建议您不要包含.cpp文件,如果您想将模板实现拆分为两个文件,则为其提供不同的扩展名(有些使用ipp(。

头文件的正常规则适用于任何#include,因此using namespace std是一个非常糟糕的主意,许多人建议根本不要使用using namespace std