【发布时间】:2014-05-05 16:39:20
【问题描述】:
这里的第一个函数在输入时编译并自动将 c char 数组转换为 c++ 字符串,但是当我尝试使用模板将该函数概括为其他类型时,它变得“愚蠢”并说它不理解该类型。
模板是否可以让函数自动从 char* 转换为 std::string 以及从 w_chart* 自动转换为 std::wstring,就像在普通函数定义中发生的那样?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> my_vector = { "apples", "bananas", "peaches"};
bool vector_has_item1(vector<string> v, string value_to_check) {
for (string s : v) {
if (s == value_to_check) return true;
}
return false;
}
template <typename T>
bool vector_has_item2(vector<T> v, T value_to_check) {
for (T s : v) {
if (s == value_to_check) return true;
}
return false;
}
int main() {
cout << vector_has_item1(my_vector, "bananas") << endl;
cout << vector_has_item2(my_vector, "bananas") << endl;
}
错误是:
test.cpp:25:48: error: no matching function for call to
'vector_has_item2(std::vector<std::basic_string<char> >&, const char [8])'
【问题讨论】:
标签: c++ string templates c-strings