Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a type is the same as a templated type

I have a user defined class

template<typename T, int N>
class MyClass
{
// Implementation
};

and I want to check on the instantiation of another class if its template parameter is an instance of MyClass

template<typename T, std::enable_if_t<!is_MyClass<T>, bool> = true>
class MapClass
{
// custom stuff here
};

template<typename T, std::enable_if_t<is_MyClass<T>, bool> = true>
class MapClass
{
// Some more stuff here
};

I tried to implement it like this but my instantiation fails because it requires two parameters. How do I make automatically extract both parameters

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template <typename T> struct is_MyClass : std::false_type {};
template <typename T, int N> struct is_MyClass<MyClass<T, N>> : std::true_type {};

Thanks

>Solution :

I suggest to write a trait is_instantiation_of_myClass that uses partial specialization:

template<typename T, int N>
class MyClass {};

template <typename C>
struct is_instantiation_of_myClass : std::false_type {};

template <typename T,int N>
struct is_instantiation_of_myClass<MyClass<T,N>> : std::true_type {};

template <typename C>
constexpr bool is_instantiation_of_myClass_v = is_instantiation_of_myClass<C>::value;

Now you can do SFINAE based on is_instantiation_of_myClass<T> or just plain specialization:

template <typename T,bool = is_instantiation_of_myClass_v<T>>
struct Foo;
template <typename T>
struct Foo<T,true> {
    static constexpr bool value = true;
};
template <typename T>
struct Foo<T,false> {
    static constexpr bool value = false;
};

int main() {
    std::cout << Foo< int >::value << "\n";
    std::cout << Foo< MyClass<int,42>>::value << "\n";
}

Live Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading