Reputation: 31
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
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;
}
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;
}
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;
}
Upvotes: 2