简体   繁体   中英

Passing string to istringsream argument of a function

I would like to work with istringstream within a function and I want the istringstream to be initialized by a string passed by value. Can I avoid the explicit istringstream iss_input(string_input); in the function body?

void f(istringstream command){
}

int main(){
    f( string("create_customer 1 Ben Finegold") );
}

The above demonstrates what I want to achieve, but it does not work. The problem I am solving is command parsing .

I'd just use a std::string as a parameter. But if you want to pass a std::istringstream , then you need to pass it explicitly to f , as the std::istringstream constructor that takes a std::string is marked explicit (#2) . Example:

f(std::istringstream{"create_customer 1 Ben Finegold"});

The code above constructs a temporary std::istringstream as the argument, which is then moved into the parameter command of your function; it uses the move constructor #3 from here .

Note that we don't need the clunky

f(std::istringstream{std::string{"create_customer 1 Ben Finegold"}});

because the const char* constructor of std::string is not explicit (#5) , and the compiler is allowed to perform at most one implicit user-defined conversion. Therefore in the first code line I posted the string literal "create_customer 1 Ben Finegold" is converted to a std::string , which is then used to explicitly construct the temporary std::istringstream argument, which is then moved into command .

I'm not quite sure what you are trying to do with that void f(...) , but I think this should do what you want:

template<typename... Args>
void f(Args&&... args)
{
    istringstream command(forward<Args>(args)...);
    // You logics...
}

int main()
{
    f("create_customer 1 Ben Finegold"s);
    //...
    return 0;
}

Edit 1

I use variadic template just in case you would like to initialize your local stream with other streams. If string you only need to initialize it with strings, you could do this:

void f(string&& str)
{
    istringstream command(forward<Args>(str));
    // You logics...
}

which is essentially the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM