繁体   English   中英

专业的类模板构造函数

[英]Specializing constructor of class template

我想专门研究类模板的构造函数。 这不起作用:

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() {}

看来我正在专门研究整个类模板。 但是我只想像上面的代码那样专门构造函数-那是行不通的。 为什么我不能只将Four的构造函数专门用于Three (我没有更改类模板的ctor的签名)?

你不能 您必须全班学习。 但是..您可以使用继承来解决:

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM