【发布时间】:2017-06-16 05:48:21
【问题描述】:
这是 C++ 程序:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int test_string(const string & str) {
return str.size();
}
void main() {
test_string(""); //can compile
vector<string> v;
string sum = accumulate(v.cbegin(), v.cend(), ""); //cannot compile
}
我想在通用 STL 函数 accumulate 的调用中使用从 const char * 到 string 的隐式转换。我知道从const char * 到字符串的转换不是明确的,所以我们可以将const char * 参数传递给需要string 类型的调用。这可以通过上面的test_string函数来证明。但是当我在accumulate 做同样的事情时,编译器抱怨:
error C2440: '=': cannot convert from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'
该代码仅在我将 "" 替换为 string("") 时才有效。我不明白为什么隐式转换适用于我的自定义函数但不适用于accumulate。你能解释一下吗?非常感谢。
PS:我使用的是 Visual Studio 2015。
【问题讨论】:
-
void main()-- 不,应该是int main() -
"我想使用从 const
char *到string的隐式转换"...但是编译器不知道你“想要”那个。表达式accumulate(v.cbegin(), v.cend(), "")中绝对没有任何内容表明应将""隐式转换为std::string。为什么您希望编译器执行转换?您希望编译器如何确定转换是必要的?
标签: c++ string templates implicit-conversion