Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 需要使用空字符串作为模板参数_C++_Templates_Oop - Fatal编程技术网

C++ 需要使用空字符串作为模板参数

C++ 需要使用空字符串作为模板参数,c++,templates,oop,C++,Templates,Oop,我希望有一个类来存储一对不同类型的变量,但我需要将变量的零或空默认值作为模板参数传递。我可以对int或double这样做,但如何对string这样做呢?我知道C++目前没有字符串参数,但横向设计是什么。我需要这样的东西: #include <iostream> #include <string> using namespace std; template <typename atype, typename btype, atype anull, btype bn

我希望有一个类来存储一对不同类型的变量,但我需要将变量的零或空默认值作为模板参数传递。我可以对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;
}

不能将非整数类型作为模板参数传递,指针和引用除外。您可能希望的最佳行为是传递一个函数,该函数为
atype
btype

返回一个“默认”值,为什么需要传递零/空值?你不能默认初始化成员吗?或者是否存在这样一种情况,即您希望将其视为“null”的值与该类型的实际默认值不同(例如,int为-1)?@Sven,是的,我希望将null作为特殊值处理,例如未初始化或未找到谢谢!这就是我最终所做的,我可以为不同类型编写模板专用函数。
error: ‘struct std::string’ is not a valid type for a template constant parameter