c++ - 类模板的特化构造函数

标签 c++ templates

我想特化类模板的构造函数。这不起作用:

template<typename T>
struct One {};

template<typename T>
struct Two {};

template<template<typename> class T, template<typename> class U>
struct Three : public T<Three<T, U>>, public U<Three<T, U>> {};

template<typename T> struct Four;

template<typename T>
struct Four
{
   Four();
};

template<template<typename> class T, template<typename> class U>
Four<Three<T, U>>::Four() {}

int main(int argc, char *argv[])
{
   Four<Three<One, Two> > obj;
}

但是将类模板定义更改为此有效:

template<typename T> struct Four;

template<template<typename> class T, template<typename> class U>
struct Four<Three<T, U>>
{
   Four();
};

template<template<typename> class T, template<typename> class U>
Four<Three<T, U>>::Four() {}

这似乎是我在专门化整个类模板。但是,我只想像上面的代码那样专门化构造函数——那个不起作用的构造函数。为什么我不能专门为 Three 专门化 Four 的构造函数(我没有更改类模板的构造函数的签名)?

最佳答案

你不能。你必须特化整个类(class)。但是..您可以使用继承作为解决方法:

#include <iostream>

class something {};

template <typename T> class hidden_base {
    public:    hidden_base() {a = 1;}
    protected: int a;
};

template<> class hidden_base<something> {
    public:    hidden_base() {a = 2;}
    protected: int a;
};

template <typename T>
class your_class : public hidden_base<T> {
public:
    void lots();
    void of();
    void other();
    void member();
    void functions();
    void here();

    void show_a() {std::cout << hidden_base<T>::a << std::endl;}
};

int main() {
    your_class<long>().show_a();
    your_class<int>().show_a();
    your_class<something>().show_a();
}

这将打印:

1
1
2

关于c++ - 类模板的特化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19546872/

相关文章:

templates - 如何根据 symfony2 上登录的用户角色呈现动态菜单

javascript - 如何使用 Handlebars 解码 HTML 实体

c++ - fatal error : yaml-cpp/yaml. h:没有那个文件或目录

C++ 指针 - C - 样式字符串

c++ - 为什么在浮点文字的末尾添加 0 会改变它的舍入方式(可能是 GCC 错误)?

c++ - 为什么我不能在 vector 迭代器中直接访问?

c++ - 具有不可复制类的模板类型推导

C++ : template taking template object as parameter. 链接错误导致

c++ - 在C++中有实现模板接口(interface)的好方法吗?

c++ - 拆分 std::index_sequence 时出错