How do I get the template type of a given element at runtime in C++?

前端 未结 3 950
情话喂你
情话喂你 2021-01-18 13:26

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 i

3条回答
  •  暖寄归人
    2021-01-18 14:06

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

    template 
    T& Array::get_element(int i, T &t)
    {
        Object *o = dynamic_cast *>(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 
    T& Array::get_element(int i)
    {
        Object *o = dynamic_cast *>(vec[i]);
        if (o == 0) throw std::invalid_argument;
        return o->object;
    }
    
    f = arr.get_element(0);
    c = arr.get_element(1);
    

提交回复
热议问题