How to define string literal with character type that depends on template parameter?

前端 未结 5 1219
不知归路
不知归路 2021-02-06 07:47
template
class StringTraits {
public:
    static const CharType NULL_CHAR = \'\\0\';
    static constexpr CharType* WHITESPACE_STR = \" \";
};

         


        
5条回答
  •  后悔当初
    2021-02-06 08:00

    I've just came up with a compact answer, which is similar to other C++17 versions. Similarly, it relies on implementation defined behavior, specifically on the environment character types. It supports converting ASCII and ISO-8859-1 to UTF-16 wchar_t, UTF-32 wchar_t, UTF-16 char16_t and UTF-32 char32_t. UTF-8 input is not supported, but more elaborate conversion code is feasible.

    template 
    constexpr auto any_string(const char (&literal)[S]) -> const array {
            array r = {};
    
            for (size_t i = 0; i < S; i++)
                    r[i] = literal[i];
    
            return r;
    }
    

    Full example follows:

    $ cat any_string.cpp 
    #include 
    #include 
    
    using namespace std;
    
    template 
    constexpr auto any_string(const char (&literal)[S]) -> const array {
            array r = {};
    
            for (size_t i = 0; i < S; i++)
                    r[i] = literal[i];
    
            return r;
    }
    
    int main(void)
    {
        auto s = any_string("Hello");
        auto ws = any_string(", ");
        auto s16 = any_string("World");
        auto s32 = any_string("!\n");
    
        ofstream f("s.txt");
        f << s.data();
        f.close();
    
        wofstream wf("ws.txt");
        wf << ws.data();
        wf.close();
    
        basic_ofstream f16("s16.txt");
        f16 << s16.data();
        f16.close();
    
        basic_ofstream f32("s32.txt");
        f32 << s32.data();
        f32.close();
    
        return 0;
    }
    $ c++ -o any_string any_string.cpp -std=c++17
    $ ./any_string 
    $ cat s.txt ws.txt s16.txt s32.txt 
    Hello, World!
    

提交回复
热议问题