简体   繁体   中英

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

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

Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM