How can I specialize a typedef and its implicit type differently?

720 Views Asked by At

I have something like this:

typedef int AnotherType;
template <typename T> Func( T Value );

// And I want to specialize these two cases separately:

template <> bool Func<int>( int Value ) {...}
template <> bool Func<AnotherType>( AnotherType Value ) {...}

I don't really need to specialize for int, what I really need is to execute a different function for AnotherType. And I cannot change the definition of AnotherType or the base function.

Overloading doesn't help either because of SFINAE.

5

There are 5 best solutions below

2
On BEST ANSWER

You could use BOOST_STRONG_TYPEDEF.

3
On

The answer is no. When you typedef you create an alias for a type, not an actual type in and of itself. The compiler will treat both the same. That's why:

typedef int Foo;
typedef int Bar;

Bar bar = 1;
Foo foo = bar;

Will compile. They're both ints.

1
On

I'm pretty sure you can't have the compiler treat int and AnotherType differently. All typedef does is alias types -- it doesn't actually create a new type; by definition of the typedef construct, the compiler will treat int and AnotherType equivalenty in all cases.

If you need to have a type with just an int that IS treated differently, you should probably just make a single-member struct. Most operations on the contained int will compile to the same machine code as a bare int, but now your data type can have its own template specializations and such.

1
On

The compiler will treat both of the specializations as exactly the same, since AnotherType is just another name for int. You say you don't need to specialize for int, so just remove that specialization completely and let it specialize on whatever type AnotherType happens to work out to.

0
On

And I cannot change the definition of AnotherType or the base function.

Then you're screwed. Sorry. The only option you really have, a strong typedef, is not an option if you can't change the definition to use a strong typedef.