c++ - 错误 :sorry, 未实现:在函数模板中使用 decltype 时,函数模板签名中存在字符串文字

标签 c++ c++11 templates 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 时出现错误。

sorry, unimplemented: string literal in function template signature auto fcn(It beg, It end) -> decltype(*beg +"name"){

这是我对所发生情况的解释:函数模板 fcn 的返回类型将从表达式 decltype(*beg + "name") 推导出来。因此 *beg 是对元素的引用,在我们的例子中 *beg 是对字符串的引用,即 string& ,然后是 * beg + "name" 是一个右值字符串。因此 decltype(*beg + "name") 将为我们提供一个类型 string。但是在函数模板 fcn 的定义中,我们返回 string& ,因此函数的返回类型(string)和函数返回值的类型(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*begstd::string& .

关于c++ - 错误 :sorry, 未实现:在函数模板中使用 decltype 时,函数模板签名中存在字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67344216/

相关文章:

c++ - 为什么 std::map::erase 返回 int 而不是 bool?

c++ - 如何获取 `std::function` 的参数数量?

c++ - 编译时和运行时数组的一个模板类(名称),代码重复很少

c++ - 如何从结构中提取最高索引的特化?

c++ - 模板对象声明和初始化: manually call template constructor to bypass standard constructors calls order

c++ - 为什么std::forward_list::: remove和std::erase <std::forward_list>具有不同的值类型?

c++ - 有没有比 allocator_type 更好的方法来区分可调整大小的容器?

c++ - 用c++创建一个定时游戏

c++ - 编写可以处理隐式共享但对不可复制类型(如 unique_ptr)关闭它的容器?

c++ - 如何在 std::function 上创建一个钩子(Hook)?