首页 > 解决方案 > 错误的自动演绎c++14

问题描述

我对“自动”返回类型函数有一个奇怪的行为。任何人都知道为什么第二个函数调用返回一个 int 而不是 double 吗?

编译器版本:g++ (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609

#include <string>
#include <iostream>

double operator+(const int& a,const std::string& b){
    return 3.4;
}
auto f(){
    return 3.4;
}
auto sum(auto a, auto b){
    return a + b;
}

int main(){
    std::cout<< sum(1.0, std::string("hello")) <<std::endl;
    std::cout<< sum(1, std::string("hello")) <<std::endl;
    std::cout<< f() << std::endl;
}
//3.4
//3
//3.4

标签: c++c++14auto

解决方案


首先,自动函数参数不是标准的 C++。这是一个 gcc 扩展,期待标准委员会的一些工作。有一次,有人谈论通过引入概念来允许这种语法。我不知道情况是否仍然如此。

至于奇怪的行为,它看起来只是一个在 gcc 5.5.0 和 gcc 6.1.0 之间修复的编译器错误


推荐阅读