Jarek C
Jarek C

Reputation: 1261

Is it possible to make a template specialization to be equal to another type

If I have e.g.:

template <class T>
class MyOptional { /*...*/ };

I know that I can define a specialization e.g. for T = bool which will have a different (separate) implementation:

template <> class MyOptional<bool> { /*...*/ };

But is it possible to say that this T=bool specialization equals to another type (e.g. MyOptBool)? Something like this:

class MyOptBool { /*...*/ };
using Optional<bool> = MyOptBool;  /* impossible but looking for similar functionality */

The only think I have found is using inheritance:

class MyOptBool { /*...*/ };
template <> class MyOptional<bool> : public MyOptBool {
  using MyOptBool::MyOptBool;
};

1st question: Is there any more elegant solution? (just for curiosity + I have some conversion issues, etc.).

2nd question: Is the "workaround" using inheritance for declaring two classes equal commonly used (in some important libraries, etc.)?

Upvotes: 4

Views: 719

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

One possible approach that allows Optional<T> to resolve in this fashion, even though it's not actually ending up specializing MyOptional, per se:

template<class T>
class MyOptional {};

class MyOptBool {};

template<class T>
struct OptionAlias {

    typedef MyOptional<T> type;
};

template<>
struct OptionAlias<bool> {

    typedef MyOptBool type;
};


template<typename T>
using Optional = typename OptionAlias<T>::type;

void foo()
{
    Optional<int> x;

    Optional<bool> y;
    MyOptBool z=y;
}

Upvotes: 7

Related Questions