Inconsistency between std::string and string literals

后端 未结 6 1461
耶瑟儿~
耶瑟儿~ 2020-12-28 12:30

I have discovered a disturbing inconsistency between std::string and string literals in C++0x:

#include 
#include          


        
6条回答
  •  庸人自扰
    2020-12-28 13:14

    The inconsistency can be resolved using another tool in C++0x's toolbox: user-defined literals. Using an appropriately-defined user-defined literal:

    std::string operator""s(const char* p, size_t n)
    {
        return string(p, n);
    }
    

    We'll be able to write:

    int i = 0;     
    for (auto e : "hello"s)         
        ++i;     
    std::cout << "Number of elements: " << i << '\n';
    

    Which now outputs the expected number:

    Number of elements: 5
    

    With these new std::string literals, there is arguably no more reason to use C-style string literals, ever.

提交回复
热议问题