Suppose I have
class A {};
template<typename T, typename U> class Wrapper {};
I'm trying to check if the wrapper's first inner type is A.
typeCheck(new A(), new Wrapper<A,B>); // expect true
typeCheck(new A(), new Wrapper<C,B>); // expect false
What's the best approach to do it?
I've tried template partial specialization but did not have luck.
Here is the code I tried:
template<typename T> struct get_inner {
using type = T;
}
template<typename T, typename U>
struct get_inner<Wrapper<T,U>> {
using type = T;
}
std::cout<< typeid(get_inner<decltype(new Wrapper<A,B>)>::type);
The console shows the same wrapper type instead of the inner type A. Is there anything mistake here?
The type of
new Wrapper<A,B>is a pointer to theWrapper<A,B>, notWrapperitself. Therefore, it doesn't suit to your specialization, and chose the first base template, wheretypeis equal to the passed type, which isWrapper<A,B>*.Instead, you should have written
Note that, the
decltypeis also unnecessary because you are passing the template type itself already.Since you are trying to see check the type at compile time, I would suggest using
std::is_sameas well. For exampleSee a demo
Well, there are many ways!
One way is to do, like
std::is_same_v, in standard type traits, you can write traits for this directly:And you would use it like
See a demo
However, that is not generic enough to change the type to be checked. There, I would suggest something similar to your original implementation.
I used, template template class specialization, in case you want to make it more generic and use it for other similar class templates.