0

I want to pass variable-length parameters in the function, concatenate these parameters with commas, and finally return the form of the string with parentheses. If the parameter type is a string or char *, then automatically With single quotes, how does this work? Thank you! For example: join (1, 2, "hello", 3, "world") returns the string "(1, 2, \"hello\", 3, \"world\")"

ben
  • 59
  • 5
  • 1
    Can you show the program you've already written, and explain how exactly your program doesn't work or doesn't produce the expected results? You have to show your work first, and it must be a good-faith real attempt to implement your program and not a few token lines of code, before asking for help on stackoverflow.com. We don't write entire programs for other people, here. For more information, see [ask] questions, take the [tour], and read the [help]. – Sam Varshavchik Feb 16 '20 at 01:46
  • `(1, 2, "hello", 3, "world")` isn't a string – M.M Feb 16 '20 at 01:48
  • Does this answer your question? [Variable number of arguments in C++?](https://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c) – Maifee Ul Asad Feb 16 '20 at 01:57

1 Answers1

0

You could create some function templates to do the job.

#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'
    ;
}

Output:

(1, 2.3, "hello", 4, "world")
()
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108