Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c++ - Is there an easy way to combine strings as function parameter?

Let's say I have a C++ function

void foo(std::string str) {
    std::cout << str << "
";
}

Now, in the equivalent Java I could call the function with a combination of various types and it would automatically be concatenated, for example:

foo("test " + intValue + " " + stringValue + "...");

This does not work in C++, but is there a way in modern C++ to achieve the same? The only solution I have found is to create a stringstream variable and do the concatenation there. However, that seems like a lot of overhead for such a common use case.

question from:https://stackoverflow.com/questions/65857929/is-there-an-easy-way-to-combine-strings-as-function-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can wrap std::stringstream in a function and use that:

#include <string>
#include <sstream>


void foo(std::string){}

template<typename...Args>
std::string concat(Args&&...args){
    std::stringstream ss;
    (ss << ... << args);
    return ss.str();
}

int main(){
    int intValue=12;
    std::string stringValue="hello";
    foo(concat("test ",intValue," ",stringValue,"..."));
}

std::string supports concatenation by +, but primitives types do not. So, you can wrap them in std::to_string but that is not so nice.

Allowing "hello"+5 is too dangerous because "hello" is one easy step from being const char* which would trigger pointer arithmetic instead.

From C++20, there is std::format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...