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

标签 c++ function c++11 stringstream istringstream

我想在一个函数中使用 istringstream,我希望 istringstream 由按值传递的 string 初始化。我可以避免函数体中显式的 istringstream iss_input(string_input); 吗?

void f(istringstream command){
}

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

上面演示了我想要实现的目标,但它不起作用。我正在解决的问题是command parsing .

最佳答案

我只使用 std::string 作为参数。但是如果你想传递一个std::istringstream,那么你需要将它明确地传递给f,作为std::istringstream构造函数需要一个 std::string is marked explicit (#2) .示例:

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

上面的代码构造了一个临时的std::istringstream作为参数,然后将其移入函数的参数command;它使用来自 here 的移动构造函数#3 .

请注意,我们不需要笨重的东西

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

因为 std::stringconst char* 构造函数 is not explicit (#5) , 并且编译器最多可以执行一个用户定义的隐式转换。因此,在我发布的第一行代码中,字符串文字 "create_customer 1 Ben Finegold" 被转换为 std::string,然后用于显式构造临时 std::istringstream 参数,然后移入 command

关于c++ - 将字符串传递给函数的 istringsream 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978249/

相关文章:

C++如何实现可停止的 future 函数调用?

jQuery:如果值等于 0,则停止递减文本框值

javascript - 如何将多个事件应用于同一个函数

c++ - 为什么 clang 和 gcc 在这个虚拟继承代码上意见不一?

c++ - 作为对象字段的右值引用

c++ - 将具有不同类型的 vector 作为初始化列表传递给函数

c++ - 具有不同签名的类方法特化

javascript - 使用 jquery 将数字传递给 for 循环函数

c++ - 名称查找和类范围

c++ - 为 C++ 类播种 rand()