我想要一个类来存储一对不同类型的变量,但我需要将变量的零或空默认值作为模板参数传递。我可以对 int 或 double 执行此操作,但如何对 string 执行此操作?我知道c++目前没有字符串参数,但是后来的设计是什么。我需要这样的东西:
#include <iostream>
#include <string>
using namespace std;
template <typename atype, typename btype, atype anull, btype bnull>
class simpleClass {
public:
atype var1;
btype var2;
simpleClass<atype, btype, anull, bnull> *parent; // pointer to parent node
simpleClass(); ~simpleClass();
};
template <typename atype, typename btype, atype anull, btype bnull>
simpleClass<atype, btype, anull, bnull>::simpleClass() { var1 = anull; var2 = bnull;
parent = NULL; }
template <typename atype, typename btype, atype anull, btype bnull>
simpleClass<atype, btype, anull, bnull>::~simpleClass() {}
int main() {
simpleClass<string, int, "", 0> obj;
obj.var1 = "hello";
obj.var2 = 45;
cout << obj.var2;
return 0;
}
编译这个,我明白了
error: ‘struct std::string’ is not a valid type for a template constant parameter
最佳答案
您不能将非整数类型作为模板参数传递,指针和引用除外。您希望的最佳行为是传递一个为 atype
和 btype
返回“默认”值的函数。
关于c++ - 需要有空字符串作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6420709/