我不能使用运算符 ""sv 作为 fstream() 的参数吗?

问题描述

#include<iostream>
#include<fstream>

using namespace std::literals;
int main()
{

    auto a = "st"sv;
    std::ifstream in("test.txt"sv,std::ios::in); //error C2664
    std::ifstream in("test.txt"s,std::ios::in);  
}

我正在使用视觉工作室。我不能在 fstream 上使用 string-view literal ""sv 吗?还是我必须设置一些东西?

解决方法

没有。你不能。

您不能使用它,因为 std::ifstream 没有接受 std::string_view ref 的构造函数 并且 std::string_viewif_stream 接受的类型之间没有隐式转换,因此您必须使用 staic_caststd::string

的构造函数进行转换

如果你有一个std::string_view(左值),你可以按如下方式使用

#include<iostream>
#include<fstream>

using namespace std::literals;
int main()
{

    auto a = "st"sv;
    auto file_location = "test.txt"sv;
    std::ifstream in(std::string(file_location),std::ios::in);  
}

Demo

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...