简体   繁体   English

将字符串传递给函数的istringsream参数

[英]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. 我想在一个函数中使用istringstream ,我希望istringstream由值传递的string初始化。 Can I avoid the explicit istringstream iss_input(string_input); 我可以避免显式的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. 我只是使用std::string作为参数。 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) . 但是,如果要传递std::istringstream ,则需要将其显式传递给f ,因为采用std::stringstd::istringstream构造函数被标记为显式(#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; 上面的代码构造了一个临时的std::istringstream作为参数,然后将其移到函数的parameter command中。 it uses the move constructor #3 from here . 它从这里开始使用move构造器#3。

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. 因为std::stringconst char*构造函数不是显式的(#5) ,并且允许编译器执行最多一次隐式的用户定义转换。 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 . 因此,我在第一行代码中将字符串文字"create_customer 1 Ben Finegold"转换为std::string ,然后将其用于显式构造临时std::istringstream参数,然后将其移入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: 我不太确定您要使用那个void f(...)做什么,但是我认为这应该可以满足您的要求:

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 编辑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. 基本上是一样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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