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

查看:19
本文介绍了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 值,并指出无论如何它对于内置程序都是多余的(例如,返回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.

虽然 Sutter 在使用 Lakos 按值返回非内置类型的对象时似乎不同意返回 const 值还是非常量值,但他通常同意返回内置类型的 const 值 (例如 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天全站免登陆