c++ type aliases ambiguity when initializing fully specialized template

61 Views Asked by At

I am trying to initialize my template class with a type alias as template parameter, but only the specialized version of my class is created. I understand the problem is in the ambiguity of my aliases. Is there a workaround?

#include <iostream>

using Type1 = size_t;
using Type2 = size_t;

template <class Type>
class SomeClass {
public:
    void doSomething() {
    }
};

template <>
class SomeClass<Type1> {
public:
};

int main() {
    SomeClass<Type1> someClass1;    // SomeClass<Type1> is initialized

    SomeClass<Type2> someClass2;    // ... and also SomeClass<Type1> is initialized ???
    someClass2.doSomething();       // and therefor doSomething() is not working...
}
1

There are 1 best solutions below

2
463035818_is_not_an_ai On

What you ask for is not possible. Not directly. Type aliases merely introduce a name that refers to the type. In your code Type1 and Type2 really are the same type.

What you can do: A level of indirection.

#include <iostream>


template <class Type>
class SomeClass {
public:
    void doSomething() {
    }
};


struct Type1 {
    using type = size_t;    
};
struct Type2 {
    using type = size_t;
};

template <>
class SomeClass<Type1> {
public:
};


int main() {
    SomeClass<Type1> someClass1;    

    SomeClass<Type2> someClass2;    
    someClass2.doSomething();       
}

And what before used Type in SomeClass now uses typename Type::type. Now SomeClass<Type1> and SomeClass<Type2> are two different instantiations, nevertheless they can use the same type.