Search code examples
c++c++17fstreamstring-view

Can't I use operator ""sv for the parameter of 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);  
}

I'm using visual studio. Can't I using the string-view literal ""sv on fstream? or Am I have to set something?


Solution

  • No. You can't.

    You can't use it because there is no ctor for std::ifstream that accepts an std::string_view ref and there is no implicit conversion between std::string_views and the types if_stream accepts, hence you have to make a conversion using staic_cast or the constructor of std::string


    If you have an std::string_view (lvalue), you can use it as follows

    #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