如何在C++中专门化模板类构造函数



我正在练习C++,我想使用模板实现一些数据结构。

我想为List<char>创建一个接受C++string作为参数的构造函数,但我不想为其余类型创建这样的构造函数(例如,从string创建List<double>没有多大意义(。

有没有一种方法可以在C++中实现这一点?

这是我的代码:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
template <typename T> class CollectionInterface {
public:
virtual T get();
virtual void set(int index, T value);
virtual void add(T value);
virtual int length();
};
template <typename T> class ListItem {
public:
T value;
ListItem* next;
ListItem* prev;
};
template <typename T> class List: public CollectionInterface<T> {
public:
List(){}
List(T* arr, int length){
init(arr,length);
}
~List(){
}
protected:
void init(T* arr, int length){
}
ListItem<T>* first;
ListItem<T>* last;
};
template<char> class List<char> {
public:
List<char>(string s){
char char_array[s.length() + 1];
strcpy(char_array, s.c_str());
this->init(char_array,s.length());
}
};
int main()
{
List<char> list("Hello World!");
//cout << "Hello World!" << endl;
return 0;
}

它显示以下错误:

第40行:"List"的部分专用化不使用其任何模板参数

第45行:"List<char>'

要想做什么,不需要专门化整个List类。只需为List<T>类提供一个用于string输入的重载构造函数,然后使用SFINAE为非char列表禁用该构造函数,例如:

template <typename T> class List: public CollectionInterface<T> {
public:
...
template <typename U = T>
List (typename enable_if<is_same<U, char>::value, string>::type const &s)
{
init(const_cast<char*>(s.c_str()), s.length());
}
...
};

在线演示

最新更新