const 返回类型何时会干扰模板实例化?

When does a const return type interfere with template instantiation?(const 返回类型何时会干扰模板实例化?)
本文介绍了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 返回类型何时会干扰模板实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)