Template specialization and alias template deduction difference

南笙酒味 提交于 2019-12-12 07:51:24

问题


I'm struggling to understand how deduction works in the following case:

template<class Category, Category code>
struct AImpl
{ };

template<class Category, Category code>
struct AHelper
{
    using type = AImpl<Category, code>;
};

template<class Category, Category code>
using A = typename AHelper<Category, code>::type;

template<int code>
void doSomething(A<int, code> object)
{
}

Following is the test code:

A<int, 5> a1;
doSomething(a1); // This does not compile
doSomething<5>(a1); // This compiles

Why a1 is not deduced in this context?

If you modify A in the following way instead:

template<class Category, Category code>
struct A
{ };

Both work. Anyone knows why?

[edit] question linked to Mixing aliases and template specializations


回答1:


Why a1 is not deduced in this context?

Because the template argument of doSomething appears in a non-deduced context. An alias template stands almost exactly for what it aliases. And yours is defined as follows:

template<class Category, Category code>
using A = typename AHelper<Category, code>::type;

To deduce code, the compiler will need to deduce something on the left of :: and that is a non-deduced context. Template argument deduction won't even attempt to deduce something if it appears as an argument to the left of the scope resolution operator.

It's not without cause that this is an undeduced context. Remember that templates may be specialized. I could add this:

template<Category code>
struct AHelper<int, code>
{
    using type = BImpl<code>; // My own class!
};

A compiler will need to look at all the code in the entire program and try all the types to be sure nothing nefarious is happening for it to be certain that a1 really matches as typename AHelper<Category, code>::type. That's intractable. So a mapping by meta-functions is a one way street only. You can't ask the compiler to deduce the source type (or non-type argument) from the target type.



来源:https://stackoverflow.com/questions/55967949/template-specialization-and-alias-template-deduction-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!