Twifty
Twifty

Reputation: 3378

Testing template parameter for equality

Let's say I have a template class defined as:

template < typename A, typename B >
class something { ... }

How can I test if types A and B are of the same type? I know this can be done at runtime with typeid, but I really need this to be a compile time test.

Also, How can I specialize the class if types A and B are equal?

In the real world, A would be an stl container of some sort, std::string for example, and B would be a char or wchar_t. Internally I already check the containers value_type (compile error if not what expected). If B is the same as the containers value_type, most of the code in the class will become redundant.

Upvotes: 1

Views: 1792

Answers (3)

neuront
neuront

Reputation: 9612

How about this

template <typename A, typename B>
struct EnsureSameType {};

template <typename A>
struct EnsureSameType<A, A> {
    typedef int the_template_types_are_different;
};

int main()
{
    /* this should compile */
    typedef EnsureSameType<std::string::value_type, char>::the_template_types_are_different _;
    /* this should fail, and you will see the compiler
       remind you that the_template_types_are_different */
    typedef EnsureSameType<std::string::value_type, wchar_t>::the_template_types_are_different _;
    return 0;
}

Upvotes: 1

Alex1985
Alex1985

Reputation: 658

You can check if the types are the same using:

std::is_same<A, B>::value

it will return true when they are.

Upvotes: 4

Sebastian Mach
Sebastian Mach

Reputation: 39089

Also, How can I specialize the class if types A and B are equal?

By exactly that, specializing:

template <typename A>
class something<A,A> { ... }

Templates use pattern matching for their parameter lists, like also seen in many functional programming languages.

How can I test if types A and B are of the same type?

You can use std::is_same, or use specialization as above. It depends on your exact use case.

Upvotes: 6

Related Questions