Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

your syntax in creating a struct is wrong .
change

    MyString<char>(narrow_str); // error C2040

to

    MyString<char> myString(narrow_str); 

will be ok.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top