错误:抱歉,未实现:在函数模板中使用 decltype 时函数模板签名中的字符串文字

问题描述

您好,我正在尝试了解模板的工作原理并尝试不同的示例。执行以下代码时出现错误。首先,我正在编写代码,然后将编写我认为正在发生的事情。

代码片段 1

#include <iostream>
#include<vector>
#include<string>

template<typename It>
auto fcn(It beg,It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
    
    return *beg;
}
int main()
{   
    std::vector<std::string> stringVector = {"firstElement","secondElement"};
    std::vector<std::string>::iterator beg = stringVector.begin();
    
    decltype(*beg + "k") l = "anothername";//this is okay and is working here.
    
    
    std::string s = fcn(stringVector.begin(),stringVector.end());
   
  
   return 0;
}

在编译/执行代码段 1 时出现错误

抱歉,未实现:函数模板签名中的字符串字面量 auto fcn(It beg,It end) -> decltype(*beg +"name"){

这是我对发生的事情的解释:函数模板 fcn 的返回类型将从表达式 decltype(*beg + "name") 中推导出来。所以 *beg 是对元素的引用,在我们的例子中,*beg 是对字符串的引用,即 string&,然后 *beg + "name"一个右值字符串。所以 decltype(*beg + "name") 会给我们一个类型 string。但是在函数模板 fcn 的定义中,我们返回了 string&,因此函数的返回类型(字符串)与函数返回的值的类型(字符串&)不匹配,我们得到了错误。但是现在就像在第二个代码片段中一样,我将 return *beg; 替换为 std::string temp = "name"; return temp;,返回类型和返回值的类型应该匹配。问题是在第二种情况下我仍然收到错误。为什么我会收到此错误,我该如何解决?我对正在发生的事情的解释是否正确?

代码片段 2

auto fcn(It beg,It end) -> decltype(*beg +"name"){ //why isn't decltype(*beg + "name") working here??
    std::string temp = "name";
    return temp;
}

解决方法

这是 GCC 错误 47488,已在 GCC 9 中解决。升级您的编译器。

函数体无关紧要。如果表达式包含字符串文字,GCC 根本无法推断出任何内容,因此它在 decltype(*beg + "name") 处放弃,当 std::string*beg