gpt4 book ai didi

c++ - 需要将空字符串作为模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 01:19:10 25 4
gpt4 key购买 nike

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

最佳答案

您不能将非整数类型作为模板参数传递,指针和引用除外。您可能希望的最佳行为是传递一个函数,该函数返回 atypebtype 的“默认”值。

关于c++ - 需要将空字符串作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6420709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com