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

How to check if an object is an instance of template class of multiple template arguments and that one of said arguments fulfills some condition?

From How to check if an object is an instance of a template class of multiple template arguments in C++? I got the following trait to check whether a type is a particular template instantiation of a templated type of several template arguments:

template <typename T1, typename T2>
struct A
{
};

template <typename Type>
struct IsA: std::false_type
{
};

template <typename T1, typename T2>
struct IsA<A<T1, T2>> : std::true_type
{
};

How would one additionally add the condition that the second type T2 fulfills some other condition?
I tried doing

template <typename Type>
struct IsA: std::false_type
{
};

template <typename T1, typename T2, std::enable_if_t<SomeCondition<T2>::value>>
struct IsA<A<T1, T2>> : std::true_type
{
};

but am getting the error

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

error: template parameters not deducible in partial specialization:

>Solution :

You were on the right track:

#include <type_traits>
#include <iostream>

template <typename T1, typename T2>
struct A
{
};

template <typename Type, typename=void>
struct IsA: std::false_type
{
};

template <typename T1, typename T2>
struct IsA<A<T1, T2>, std::enable_if_t<std::is_same_v<T2, int>>>
    : std::true_type
{
};

int main()
{
    std::cout << IsA<int>::value << "\n";

    std::cout << IsA<A<char, char>>::value << "\n";

    std::cout << IsA<A<char, int>>::value << "\n";
    return 0;
}

In this trivial example the "some condition" is just a std::is_same_v<T2, int>, only for the sake of an example.

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