什么时候const返回类型干扰模板实例化? [英] When does a const return type interfere with template instantiation?

查看:108
本文介绍了什么时候const返回类型干扰模板实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Herb Sutter的 GotW#6

From Herb Sutter's GotW #6


对于非内置返回类型,返回值通常应为const。 ...

Return-by-value should normally be const for non-builtin return types. ...

注意:Lakos(第618页)反对返回const值
,并注意到它对于builtins来说是多余的
例如,返回const int),他注意到
会干扰模板实例化。

Note: Lakos (pg. 618) argues against returning const value, and notes that it is redundant for builtins anyway (for example, returning "const int"), which he notes may interfere with template instantiation.

不同意在通过Lakos返回一个非构建类型的对象时是返回一个常量值还是非常量值,他通常同意返回一个内置类型的常量值(例如const int)不是一个好的主意。

While Sutter seems to disagree on whether to return a const value or non-const value when returning an object of a non-built type by value with Lakos, he generally agrees that returning a const value of a built-in type (e.g const int) is not a good idea.

虽然我明白为什么这是无用的,因为返回值不能修改,因为它是一个右值,我找不到一个例子可能会干扰模板实例化。

While I understand why that is useless because the return value cannot be modified as it is an rvalue, I cannot find an example of how that might interfere with template instantiation.

请给我一个例子,说明如何为一个返回类型的const限定符可能会干扰模板实例化。

Please give me an example of how having a const qualifier for a return type might interfere with template instantiation.

推荐答案

这里是一个简单的例子,涉及函数指针:

Here's a simple example involving function pointers:

const int f_const(int) { return 42; }
int f(int) { return 42; }

template <typename T>
void g(T(*)(T))
{
    return;
}

int main()
{
    g(&f_const); // doesn't work:  function has type "const int (*)(int)"
    g(&f);       // works: function has type "int (*)(int)"
}

注意,Visual C ++ 2010不正确地接受两者。 Comeau 4.3.10和g ++ 4.1.2正确地不接受 g(& f_const)调用。

Note that Visual C++ 2010 incorrectly accepts both. Comeau 4.3.10 and g++ 4.1.2 correctly do not accept the g(&f_const) call.

这篇关于什么时候const返回类型干扰模板实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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