阅读可变参数函数时,我发现了一个 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;
}
错误:
invalid operands of types 'const char [7]' and 'const char [6]' to binary 'operator+'
我希望它连接 Hello!
和 World
并打印出 Hello!World
。
有什么问题?
最佳答案
字符串文字不是 std::string
对象。没有为字符数组定义operator +
。
正如您的编译器告诉您的那样,"Hello!"
的类型为 const char[7]
,而 "World"
的类型为 常量字符[6]
。尝试声明这些类型的两个变量并计算它们的总和:
int main()
{
char const a[7] = "Hello!";
char const b[6] = "World";
(a + b);
}
编译器会显示类似的错误:
error: invalid operands of types 'const char [7]' and
'const char [6]' to binary 'operator+'
为了使您的代码正常工作,将两个字符串文字中的至少一个包装到 std::string
对象中(operator +
的两个相应重载存在于 std::string
对象):
auto x = sum(std::string("Hello!") + "World");
或:
auto x = sum("Hello!" + std::string("World"));
当然,您也可以将两个参数都包装起来,但这是不必要的。
关于c++ - Variadic 函数不接受字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056766/