如何在C ++中获取运行时给定元素的模板类型? [英] How do I get the template type of a given element at runtime in C++?

查看:90
本文介绍了如何在C ++中获取运行时给定元素的模板类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个简单的Array类,该类可以保存任何类型的对象,例如可以在一个对象中保存多种类型数据的矢量. (这是出于学习目的.)

I'm designing a simple Array class with the capability of holding any type of object, like a vector that can hold multiple types of data in one object. (This is for learning purposes.)

我有一个名为Container的空基类:

I have an empty base class called Container:

class Container {};

还有一个名为Object的模板化子类:

And a templatized subclass called Object:

template <class T>
class Object : public Container {
    T& object;
public:
    Object(T& obj = nullptr) : object(obj) {}
};

我有一个Array类,其中包含指向Container s的指针的vector指针,该指针用于保存Object s:

I have an Array class which holds a vector of pointers to Containers which I use to hold Objects:

class Array {
    std::vector<Container *> vec;
public:
    template <class T>
    void add_element(const T&);
    auto get_element(int);
};

add_element将元素存储到Object s中,然后将其放入vec中:

add_element stores elements into Objects and puts them into vec:

template <class T>
void Array::add_element(const T& element)
{
    vec.push_back(new Object<T>(element));
}

get_element从其Object中删除该元素,并将其传递回调用方.这就是我的问题所在.为了从Object中删除该元素,我需要知道它是什么类型的Object:

get_element removes the element from it's Object and passes it back to the caller. This is where my problem lies. In order to remove the element from the Object, I need to know what type of Object it is:

auto Array::get_element(int i)
{
    return (Object</* ??? */> *)vec[i])->object;
}

我是否可以通过某种方式找出要存储的对象类型?

Is there some way for me to find out what sort of object I'm storing?

编辑:由于人们声称这是不可能的,因此如何处理.有没有一种在类内部实际存储类型信息的方法? (我知道您可以用红宝石做到这一点).如果可以的话,可以在每个Object中存储get_element的返回类型.

since people are claiming that this is not possible, how about this. Is there some way of actually storing type information inside of a class? (I know you can do that in ruby). If I could do that, I could store the return type of get_element in each Object.

推荐答案

我正在为您的get_element遵循此模板的思路.

I was thinking something along the lines of this template for your get_element.

template <class T>
T& Array::get_element(int i, T &t)
{
    Object<T> *o = dynamic_cast<Object<T> *>(vec[i]);
    if (o == 0) throw std::invalid_argument;
    return t = o->object;
}

Array arr;
double f;
int c;

arr.get_element(0, f);
arr.get_element(1, c);

但是,您也可以使用它:

But alternatively, you could use this:

template <class T>
T& Array::get_element(int i)
{
    Object<T> *o = dynamic_cast<Object<T> *>(vec[i]);
    if (o == 0) throw std::invalid_argument;
    return o->object;
}

f = arr.get_element<double>(0);
c = arr.get_element<int>(1);

这篇关于如何在C ++中获取运行时给定元素的模板类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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