现在,我使用的函数'JoinStrings'只能加入数据类型std::string。我现在需要加入整数。所以我希望重构它。但我失败了。我很高兴听到“你不能这样做”,因为我真的不知道以这种方式重用这些代码是否合理。
调用部分:
int main(int argc, char* argv[]) {
vector<int> integers;
string str = JoinStrings(integers);
cout << str << endl;
}
我未能实施的部分:
#include <string>
template <class ConstForwardIterator>
void JoinStrings(const ConstForwardIterator& begin,
const ConstForwardIterator& end,
const std::string& delimiter,
std::string* output) {
output->clear();
for (ConstForwardIterator iter = begin; iter != end; ++iter) {
if (iter != begin) {
output->append(delimiter);
}
output->append(*iter);
}
}
// What data type should be declared for IntegerConstForwardIterator?
template<>
void JoinStrings(const IntegerConstForwardIterator& begin,
const IntegerConstForwardIterator& end,
const std::string& delimiter,
std::string* output) {
output->clear();
for (IntegerConstForwardIterator iter = begin; iter != end; ++iter) {
if (iter != begin) {
output->append(delimiter);
}
output->append(std::to_string(*iter));
}
}
template <class ConstForwardIterator>
std::string JoinStrings(const ConstForwardIterator& begin,
const ConstForwardIterator& end,
const std::string& delimiter) {
std::string output;
JoinStrings(begin, end, delimiter, &output);
return output;
}
template <class Container>
std::string JoinStrings(const Container& container,
const std::string& delimiter = " ") {
return JoinStrings(container.begin(), container.end(), delimiter);
}