c++ - Variadic 函数不接受字符串对象

标签 c++ templates c++11

阅读可变参数函数时,我发现了一个 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/

相关文章:

c++ - tuple/tie的返回值优化

c++ - 在可变参数模板中使用 lambda 调用 std::make_tuple - 这应该在 C++11 中工作吗?

c++ - 是否可以将逻辑文件夹的内容与 NetBeans C++ 中的物理文件夹同步?

c++ - 如何使概念失败并显示自定义错误消息(C++ 20)

c++ - MFC 应用程序 DialogBased 使用 propertyPage,CDialog 的 DoModal() 不打开任何对话框

c++ - array<int,2> dim 在这段代码中是什么意思?

c++ - iostream 是否使用重载或模板?

c++ - 推断函数指针或仿函数的返回类型

c++ 11不受限制的联合示例

c++ - 32 位与 64 位库修饰