模板化类的不同专业的向量 [英] Vector of different specializations of a templated class

查看:46
本文介绍了模板化类的不同专业的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我一直在C ++中使用模板,所以我经常遇到这个问题:我想在向量中收集模板类的不同版本的实例.

Since I have been using templates in C++, I often encounter this problem: I would like to gather instances of different versions of a templated class in a vector.

我知道这不可能直接实现,但是我想知道是否有一些解决方法来实现这一目标.

I understand this is not possible directly, but I wonder if there is some workaround to achieve this.

例如,如果我有这样的模板化类:

For example if I have the templated class like so:

enum test_e
{
  TYPE_A,
  TYPE_B
};

template <test_e TYPE>
class test
{
  void doSomething()
  {
    switch (TYPE)
    {
      ...
    }
  }
};

我想构建一个向量,在其中可以同时推动类 test 的两个专业化( TYPE_A & TYPE_B ).

I would like to build a vector where I could push both specializations (TYPE_A & TYPE_B) of the class test.

执行此操作的最佳方法是什么?

What's the best approach to do this?

推荐答案

如果要存储其他模板类,则可以创建一个父类,并在模板类中继承该类.

If you want to store different template classes, you can make a parent class and inherit that class in the template class.

我不知道您为什么要对类型使用 switch ,仅使用模板实例化即可.

And I don't know why you're using switch for types, just use template instantiation.

#include <iostream>
#include <vector>

using std::cout;
using std::endl;


class Mother {
public:
    virtual void doSomeThing() = 0;
};

template<typename T>
class Child : public Mother {
    void doSomeThing() override;
};

template<typename T> void Child<T>::doSomeThing() {
    cout << "Base Function" << endl;
}
template<> void Child<int>::doSomeThing() {
    cout << "Int template" << endl;
}

template<> void Child<float>::doSomeThing() {
    cout << "Float template" << endl;
}

int main() {

    std::vector<std::unique_ptr<Mother>> vec;

    vec.emplace_back(new Child<double>());
    vec.emplace_back(new Child<int>());
    vec.emplace_back(new Child<float>());

    vec[0]->doSomeThing();
    vec[1]->doSomeThing();
    vec[2]->doSomeThing();


    return 0;
}

输出:

Base Function
Int template
Float template

Process finished with exit code 0

这篇关于模板化类的不同专业的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆