模板类中的auto不完全使用类 [英] incomplete class usage with auto in template class

查看:102
本文介绍了模板类中的auto不完全使用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码格式正确吗?

class B;

template<class T>
class A
{
    B do_f() const;
    friend auto f(A const& a) {return a.do_f();} // #1
};

class B{};

template <class T>
B A<T>::do_f() const { return B{};}

int main()
{
    A<double> a;
    f(a);
}

如果我将#1中的auto更改为B,则会收到不完整的类型错误消息.

If I change auto in #1 by B, I got incomplete type error message.

使用auto编译gcc/clang 演示

Compile with auto for gcc/clang Demo

B失败演示

推荐答案

[dcl.fct.def.general]/2 :

在函数定义的上下文中,参数的类型或函数定义的返回类型不得为不完整或抽象的(可能具有cv限定的)类类型,除非删除了该函数([dcl.fct.def.delete]).

The type of a parameter or the return type for a function definition shall not be an incomplete or abstract (possibly cv-qualified) class type in the context of the function definition unless the function is deleted ([dcl.fct.def.delete]).

但是 [dcl.spec.auto]/10 :

实例化定义时,即使函数主体包含带有与类型无关的操作数的return语句,在声明的类型中带有占位符的函数模板也会发生

返回类型推导.

Return type deduction for a function template with a placeholder in its declared type occurs when the definition is instantiated even if the function body contains a return statement with a non-type-dependent operand.

所以对于B,它是由第一条规则构成的.但是,使用auto时,直到函数实例化之后才进行推论...到那时,类型已完成,因此就可以了.

So with B, it's ill-formed by the first rule. But with auto, deduction doesn't take place until the function is instantiated... by which point the type is complete, so it's fine.

请注意,第一个规则仅适用于定义,这就是为什么do_f()可以的原因.您可以具有返回不完整类型的声明.

Note that the first rule only applies to the definition, which is why do_f() is okay. You can have declarations which return incomplete types.

以上措辞从技术上讲不适用于这种情况.我们没有功能模板.但其目的是将其应用于任何类型的模板化对象.有一个 PR 可以通过以下方式对此进行修正:

The above wording technically doesn't apply to this case. We don't have a function template. But the intent is for it to apply to any kind of templated thing. There's a PR to editorially fix this from:

具有占位符[...]

Return type deduction for a function template with a placeholder [...]

收件人:

是功能模板或功能模板的模板实体的返回类型推论,在其中

这里确实适用.

这篇关于模板类中的auto不完全使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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