Reading about variadic functions, I found a sum function which accepts any number of any numeric type and calculate sum of them.
Having templated nature of this function, I expected it accepts string objects since operator + is defined for strings.
#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;
}
Error:
invalid operands of types 'const char [7]' and 'const char [6]' to binary 'operator+'
I expected it concatenates Hello! and World and prints out Hello!World.
What is the problem?
const char*doesn't have overloadedoperator+, like it says in the error. Pretty clear if you ask me.