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

标签 c++ templates oop

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

相关文章:

C++11/VS2010 : Returning containers of uncopyable but movable objects

c++ - 从 QImage 创建 QByteArray,反之亦然

c++ - 像在早期 C 中一样在开始时声明所有范围局部变量的编译含义?

c# - 如何从已声明为接口(interface)的基类中获取值?

c++ - 用于顺序处理的高效通用缓冲队列

c++ - 仅当将值与 TRUE 进行比较时才会警告操作中 xxx 和 bool 的不安全混合

css - Custom.css 未在 PrestaShop 1.7 中运行

C++数组作为模板参数

c++ - 如何协调将 header /源代码与模板分离的 C++ 习惯用法?

php - 如果未实例化对象,调用静态函数将返回 NULL? PHP面向对象