Keine Ahnung
Keine Ahnung

Reputation: 31

How can i get a Type of a Variable and store it in a Template Function/Class

Im trying to store the name of a Variable and use this for a templated Class But also this should be also very flexible with every Class/ type : whatever (For an Alocater) and Ive nothing found about this yet.

Here is some example Code of one of my tries:

#include<iostream>

template<typename T>
struct a{
    T*Data;

    a(T*Data):Data(Data){}
}

int main(){
    int i = 10;
    a<int>* obj1 =new a<int>(&a);

    //Later

    std::string Dat_Type= typeid(*obj1->Data).name();
    a<Dat_Type> obj2;//This Doesnt work 
}

Upvotes: 1

Views: 641

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30494

A string containing the name of a type is not the same as a type. The former exists only at runtime while the latter exists only at compile time.

What you can do is add a type alias to a that you can pass to another template:

template <typename T>
struct a {
    using value_type = T;
    //...
};

int main() {
    a<int> obj1;

    // Later

    a<decltype(obj1)::value_type> obj2;
}

Live Demo

If you can't modify your a class for whatever reason, you could use partial template specialization to extract the correct type:

template <typename T>
struct a_traits {};

template <typename T>
struct a_traits<a<T>> {
    using value_type = T;
};

int main() {
    a<int> obj1;

    // Later

    a<a_traits<decltype(obj1)>::value_type> obj2;
}

Live Demo


Of course, if you're declaring a second object of the exact same type, you don't need to do either of those things. You can just use decltype:

int main() {
    a<int> obj1;

    // Later

    decltype(obj1) obj2;
}

Live Demo

Upvotes: 2

Related Questions