【发布时间】:2013-02-24 21:16:27
【问题描述】:
阅读可变参数函数时,我发现了一个sum 函数,它接受任意数量的任意数值类型并计算它们的总和。
由于此函数具有模板化性质,我希望它接受 string 对象,因为运算符 + 是为字符串定义的。
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using namespace std;
template <typename T> T sum(T && x)
{
return std::forward<T>(x);
}
template <typename T, typename ...Args>
typename std::common_type<T, Args...>::type sum(T && x, Args &&... args)
{
return std::forward<T>(x) + sum(std::forward<Args>(args)...);
}
int main()
{
auto y = sum(1, 2, 4.5); // OK
cout << y << endl;
auto x = sum("Hello!", "World"); // Makes error
cout << x << endl;
return 0;
}
错误:
'const char [7]' 和 'const char [6]' 类型的无效操作数 二进制'运算符+'
我希望它连接 Hello! 和 World 并打印出 Hello!World。
有什么问题?
【问题讨论】:
-
const char*没有重载operator+,就像它在错误中所说的那样。如果你问我就很清楚了。