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

前端 未结 7 1935
说谎
说谎 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:31

    I don't think you can enforce to pass only a string literal to a function, but literals are character arrays, what you can enforce:

    #include 
    
    template
    void log(T) = delete; //Disable everything
    
    template 
    void log(const wchar_t (&message)[Size]) //... but const wchar_t arrays
    {
        std::cout << "yay" << std::endl;
    }
    
    const wchar_t * get_str() { return L"meow"; }
    
    int main() {
        log(L"foo"); //OK
    
        wchar_t arr[] = { 'b', 'a', 'r', '0' };
        log(arr); //Meh..
    
    //    log(get_str()); //compile error
    }
    

    Downside is that if you have a runtime character array, it will work as well, but won't work for the usual runtime c-style strings.

    But, if you can work with a slightly different syntax, then the answer is YES:

    #include 
    #include 
    
    void operator"" _log ( const wchar_t* str, size_t size ) {
      std::cout << "yay" << std::endl;
    }
    
    int main() {
      L"Message"_log;
    }
    

    Of course, both solution needs a C++11-compatible compiler (example tested with G++ 4.7.3).

提交回复
热议问题