Can a compilation error be forced if a string argument is not a string literal?

前端 未结 7 1917
说谎
说谎 2020-12-17 20:24

Let\'s say I have these two overloads:

void Log(const wchar_t* message)
{
    // Do something
}

void Log(const std::wstring& message)
{
    // Do someth         


        
7条回答
  •  旧巷少年郎
    2020-12-17 20:47

    You can't detect string literals directly but you can detect if the argument is an array of characters which is pretty close. However, you can't do it from the inside, you need to do it from the outside:

    template 
    void Log(wchar_t const (&message)[Size]) {
        // the message is probably a string literal
        Log(static_cast(message);
    }
    

    The above function will take care of wide string literals and arrays of wide characters:

    Log(L"literal as demanded");
    wchar_t non_literal[] = { "this is not a literal" };
    Log(non_literal); // will still call the array version
    

    Note that the information about the string being a literal isn't as useful as one might hope for. I frequently think that the information could be used to avoid computing the string length but, unfortunately, string literals can still embed null characters which messes up static deduction of the string length.

提交回复
热议问题