2

Let's say we want a new name for a template class ClassOrig.

template <typename T>
class ClassOrig {};
  1. Directly use using alias, this works fine.
template<typename T>
using ClassAlias = ClassOrig<T>;
  1. Use a wrapper and use using alias inside the wrapper.
template <typename T>
class ClassWrapper {
public:
    // static_assert(..., "");
    using type = ClassOrig<T>;
};

template <typename T>
using ClassAlias = typename ClassWrapper<T>::type;

The second solution has trouble deducing types implicitly. The code below cannot deduce template argument. We have to explicitly use the template argument list. I'm wondering why the 1st solution works with the code below but the 2nd solution does not?

template <typename T>
void bar(ClassAlias<T> const& v);

template <>
void bar(ClassAlias<int> const& v) {} // cannot deduce template argument, need to use bar<int>

template <typename T>
void bar(ClassAlias<T> const& v) {}

int main() {
    ClassAlias<double> a;
    bar(a); // cannot deduce template argument, need to use bar<double>
    return 0;
}
wanghan02
  • 1,227
  • 7
  • 14
  • 1
    You can't do that irrespective of a type alias. – erip Jan 22 '16 at 15:10
  • Could you explain more specifically? Thanks. – wanghan02 Jan 22 '16 at 15:15
  • `std::vector` doesn't allow implicit conversion of template types, so you shouldn't be surprised that it isn't working with a type alias either. – erip Jan 22 '16 at 15:15
  • Not a dupe, but [very related](http://stackoverflow.com/questions/30508404/implicit-conversion-of-vector-from-one-type-to-another-c). – erip Jan 22 '16 at 15:19
  • It's still the same behavior if we change std::vector to a normal template class. – wanghan02 Jan 22 '16 at 15:35
  • 3
    The template alias is replaced with `typename ClassWrapper::type` which is a non-deduced context in a parameter declaration. An explicit template argument is required. – David G Jan 22 '16 at 15:37
  • 1
    related/dupe http://stackoverflow.com/questions/29677522/cant-deduce-template-type – NathanOliver Jan 22 '16 at 15:45

0 Answers0