是否有必要使用模板参数来引用相同的类在定义? [英] Is it necessary to use template parameters to refer to same class inside definition?

查看:142
本文介绍了是否有必要使用模板参数来引用相同的类在定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是必要的:

 template <typename T>
 class A{
   T*point;
   A<T> someFunction(){} //instead of returning just "A", not "A<T>"
 }

someFunction 返回与定义的类相同类型的 A ?因为在类之外,你只能引用这个类型为 A< float> 或类似的,所以我认为这也是必要的。我发现它编译没有>因此这使奇迹,如果是一个安全的习惯,省略括号。

Will someFunction implicitly return the A of the same type as the class being defined? Because outside the class, you can only refer to this type as A<float> or similar, so I'd assumed this was necessary inside the class as well. I discovered it compiles without the <> so this made wonder if it is a safe habit to omit the brackets.

推荐答案

有效和安全的C ++来省略类定义中的模板参数。事实上,这是一个好的做法,因为你可以添加其他模板参数与默认值。您可能会忘记将 A< T> 更改为 A< T,SomeOtherParameter> ,并得到奇怪的编译时错误。然后只需返回 A 就可以了。

It's valid and safe C++ to omit the template parameters inside the class definition. In fact it's good practice, since you might add other template parameters with default values later on. You might forget to change A<T> to A<T,SomeOtherParameter> and get strange compile-time errors. Then just returning A will do it.

这篇关于是否有必要使用模板参数来引用相同的类在定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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