Search code examples
c++templatescompiler-errorstemporary-objectstype-deduction

Why can the simplest C++ code not be compiled?


template<class CharType>
struct MyString
{
    MyString()
    {}

    MyString(CharType*)
    {}
};

int main()
{
    char* narrow_str = 0;
    MyString<char>(narrow_str); // error C2040
}

My compiler is VC++ 2013 RC.

The simplest code cannot be compiled because of the error C2040.

error C2040: 'narrow_str' : 'MyString' differs in levels of indirection from 'char *'

Why?


Solution

  • The problem is this is actually not being parsed as a constructor call but as a variable definition. The problem is you already defined a variable narrow_str. You may have already known this but you can easily fix this by giving it a name.

    template<class CharType>
    struct MyString
    {
        MyString()
        {}
    
        MyString(CharType*)
        {}
    };
    
    int main()
    {
        char* narrow_str = 0;
        MyString<char> ns(narrow_str); // error C2040
    }
    

    BTW this is also the source of the most vexing parse which occurs when this type of syntax is used in a function argument.

    To be honest though I'm surprised that you got a different error because both g++ and clang gave me a clear error.