Why does GCC need extra declarations in templates when VS does not?

后端 未结 2 954
暗喜
暗喜 2021-01-01 18:10
template
class Base
{
protected:
    Base() {}
    T& get() { return t; }
    T t;
};

template
class Derived : public Base&l         


        
2条回答
  •  误落风尘
    2021-01-01 18:17

    GCC is right in this case, and Visual Studio mistakenly accepts a malformed program. Have a look at the section on Name lookup in the GCC manual. Paraphrasing:

    [T]he call to [get()] is not dependent on template arguments (there are no arguments that depend on the type T, and it is also not otherwise specified that the call should be in a [template-]dependent context). Thus a global declaration of such a function must be available, since the one in the base class is not visible until instantiation time.

    You can get around this in either of three ways:

    • The declarations you are already using.
    • Base::get()
    • this->get()

    (There is also a fourth way, if you want to succumb to the Dark Side:

    Using the -fpermissive flag will also let the compiler accept the code, by marking all function calls for which no declaration is visible at the time of definition of the template for later lookup at instantiation time, as if it were a dependent call. We do not recommend using -fpermissive to work around invalid code, and it will also only catch cases where functions in base classes are called, not where variables in base classes are used (as in the example above).

    But I would recommend against that, both for the reason mentioned in the manual, and for the reason that your code will still be invalid C++.)

提交回复
热议问题