我正在使用以下代码进行原型设计。为什么将char *传递给字符串参数会产生编译错误?
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
template<class container, class value> class Add {
public:
Add(){};
~Add(){};
void add_value(container& cont, value& val){
std::for_each(cont.begin(), cont.end(), [&val](value& v){v +=val;});
};
};
int main(int argc, char const *argv[])
{
Add<std::vector<std::string>, std::string> a;
std::vector<std::string> vec = {"a", "b", "c", "d"};
std::string foo= "1";
a.add_value(vec, foo); // compiles fine
a.add_value(vec, "1"); // generates an error
return 0;
}
,我得到了以下错误
template.cpp:28:25: error: invalid initialization of non-const reference of type ‘std::__cxx11::basic_string<char>&’ from an rvalue of type ‘std::__cxx11::basic_string<char>’
为什么它不可能通过一个char*
到string
说法?
据我所知,为了将char*
转换为std::string
并将结果传递给该函数,将执行一个隐式转换。
功能需要采取一个const引用。非const引用不能绑定到临时对象,比如将“1”转换为字符串所产生的临时对象。错误消息告诉你。 –
我在这里很好奇。为什么非const引用不能绑定到右值? – hannibal
因为C++标准没有说。 –