模板专业化与别名模板推导的区别 [英] Template specialization and alias template deduction difference

查看:66
本文介绍了模板专业化与别名模板推导的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下,我很难理解扣除的原理:

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)
{
}

下面是测试代码:

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

为什么在这种情况下不推导a1?

Why a1 is not deduced in this context?

如果您改用以下方式修改A:

If you modify A in the following way instead:

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

两者都可以。有人知道为什么吗?

Both work. Anyone knows why?

[edit]
问题链接到混合别名和模板专业化

推荐答案


为什么a1

Why a1 is not deduced in this context?

因为没有出现模板参数 doSomething 在非推论上下文中。别名模板几乎完全代表其别名。您的定义如下:

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!
};

编译器需要查看整个程序中的所有代码,并尝试所有类型确保没有发生任何邪恶的事情,以确保 a1 typename AHelper< Category,code> :: type 。太难了因此,通过元功能进行的映射仅是单向路。您不能要求编译器从目标类型中推断出源类型(或非类型参数)。

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.

这篇关于模板专业化与别名模板推导的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆