首页 > 解决方案 > 如何将可变长度参数作为字符串连接

问题描述

我想在函数中传递变长参数,用逗号连接这些参数,最后返回带括号的字符串形式。如果参数类型是字符串或者char *,那么自动加上单引号,这是怎么回事呢?谢谢!例如:join(1, 2, "hello", 3, "world") 返回字符串 "(1, 2, \"hello\", 3, \"world\")"

标签: c++

解决方案


您可以创建一些功能模板来完成这项工作。

#include <iostream>
#include <sstream>
#include <type_traits>

// a function that takes a variable amount of arguments
template<typename T, class... Args >
std::string join_helper(const T& t, Args...args) {
    std::ostringstream ss;
    using type = std::remove_cv_t<std::remove_reference_t<T>>;

    // check if " should be added    
    if constexpr(std::is_same_v<type, const char*> || 
                 std::is_same_v<type, std::string> || 
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    ss << t; // stream out the current value

    if constexpr(std::is_same_v<type, const char*> || 
                 std::is_same_v<type, std::string> || 
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    // do we have more arguments? if so, add ", " and call join_helper again
    if constexpr (sizeof...(args) > 0) {
        ss << ", ";
        ss << join_helper(args...);
    }
    return ss.str();
}

// the function you will use that adds ( and ) around the return value from join_helper
template<class... Args>
std::string join(Args...args) {
    if constexpr(sizeof...(args) > 0)
        return '(' + join_helper(args...) + ')';
    else
        return "()";
}

int main() {
    std::cout
        << join(1, 2.3, "hello", 4, std::string("world")) << '\n'
        << join() << '\n'
    ;
}

输出:

(1, 2.3, "hello", 4, "world")
()

推荐阅读