C++ 模板类,根据类型名改变类方法的行为

标签 c++ templates template-specialization

我有一个模板类,我试图根据类中的类型名对其方法进行专门化。代码的框架如下:

template <typename C> class Instance {
  protected:
    C data;
  public:
    void populateData();
    /* want to change the behavior of populateData() depending on C */
};

我如何实现上述目标?

最佳答案

我想这就是你想要的:

template <typename C> class Instance {
  protected:
    C data;
  public:
    void populateData();
    /* want to change the behavior of populateData() depending on C */
};

template<>
void Instance<int>::populateData() {
    // Do something when C is int
}

您可以将函数专门化为您想要的任何类型。

关于C++ 模板类,根据类型名改变类方法的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932330/

相关文章:

c++ - 重载 [] 但其结果在与其他运算符交互之前未解析 (c++)

C++ 模板特化

c++ - 广度优先搜索输入

c++ - 如何为 makefile 创建目标

c++ - Scala宏和C++模板的异同

C++使用子类从模板继承

c++ - 整数参数特殊值的模板特化

c++ - 使用构造函数初始化结构中的结构

c++ - 如何使用 gnu c++ 程序获取共享对象文件(.so 文件)的体系结构?