views:

112

answers:

7

Consider this code:

typedef int type1;
typedef int type2;

template <typename>
struct some_trait;

template <>
struct some_trait<type1>
{
    static const int something=1;
};

template <>
struct some_trait<type2>
{
    static const int something=2;
};

It fails because what the compiler sees is two specializations of some_trait<int>.

What's the best way around this?

+4  A: 

Best way around what exactly?

Both typenames refer to the same int type. Since there's only one type here, you only need one trait. So, "the best way around this" would be to remove the second specialization and forget about it. Done.

Is that what you wanted? If not, please, provide a more meaningful description of what you are trying to achieve.

AndreyT
James Curran
+4  A: 

I think to be able to specialize on the names type1 and type2 you'll have to make them actually be different types instead of an alias for the same type:

struct type1 {
     int data;
};

struct type2 {
    int data;
};

// ...

But if you explain more about your end-goal there might be a different/better way to accomplish what you're looking for.

Michael Burr
A: 

I don't see what you're trying to do here. In the end, both are some_trait< int > .
Tried making structs around a single int?

The Communist Duck
+1  A: 

you can have something like this if you mean explicit specialization:

enum TypeOne;
enum TypeTwo;

template <typename>
class AClass;

template <>
class AClass<TypeOne>{
 public:
  int something;
};

template <>
class AClass<TypeTwo>{
 public:
  char something;
};

AClass<TypeOne> obj1;
AClass<TypeTwo> obj2;

I also have seen something from boost libraries that can do what you want, typedef same type to different types for explicit specialization, but I don't remember what it was exactly.

Pooria
+1  A: 

It sounds like something like the following may be what you're after:

template <int arg>
class AClass
{
    static const int something=arg;
};

which would be instantiated like:

AClass<1> obj1;
AClass<2> obj2;
rlduffy
+2  A: 

That code fails because the compiler sees the same specialization occurring twice.

Your problem is that typedef, despite its name, does not define a new type. It only generates an alias for another type. type1 and type2 and int actually are just different names for the same type.

What's the best way around of this depends on what you want to achieve. If you absolutely need this specialization, you will have to come up with two distinct types. However, there might be better ways to do this.

sbi
A: 

I think you want to achieve something like this: template <typename T, T t> struct typify{ static const T something = t;}; Your 2 specializations would then be written as struct int_1 : typify<int, 1>{}; and ...

supertux