正如大家所说,C++ 中的向量只有一种类型。没有必要也没有必要依次检查每个元素的类型,这也很好,因为没有办法做到这一点。相反,您要做的是在参数类型上重载函数。像这样的东西:
string toCustomString(const string &str) {
return "foo" +str + "bar";
}
template <typename T>
string toCustomString(const std::vector<T> &vec) {
string ret;
for(size_t i = 0; i < vec.size(); ++i)
ret += toCustomString(vec[i]);
return ret;
}
现在,如果有人传入,vector<string>则toCustomString调用toCustomString(vec[i])将选择toCustomString(const string &str)重载。
如果有人将 avector<int>传入toCustomString,则代码将无法编译,因为(当前)没有toCustomString(int)重载 [*]。
如果有人通过 a vector<vector<string>>to toCustomStringthentoCustomString(vec[i])将通过 a vector<string>,见上文。
在所有三种情况下,都会调用不同 toCustomString的函数。在第一种情况下它是toCustomString<string>(const vector<string>&),这是toCustomString与第三种情况不同的模板实例化,toCustomString<vector<string>>(const vector<vector<string>>&)。中间情况尝试实例化toCustomString<int>,但由于toCustomString(v[i])不匹配它知道的任何函数而失败。
所有这些都是在编译时确定的。模板的重点是创建多个函数(或类),它们之间有特定的差异。在这种情况下,区别在于传入的向量类型。
[*] 这似乎符合您的要求,即vec[i]必须是向量或字符串,而不是任何第三个选项。例如,如果您希望 a 的返回值为vector<something_else>空,则可以添加一个包罗万象的模板:
template <typename T>
string toCustomString(const T &) {
return string();
}
当然,您可以为要处理的任何其他类型添加更多重载。