c++ - What does a compiler check for uninstantiated template code? -
for example, following code piece compiles gcc-4.9 , clang-602
class base { public: static void foo() {} void badfoo(int i) {} }; template <typename t> class derived : public base { public: void bar() { base::foo(); } void badbar() { base::badfoo(); } // compiles ok //static void badbar() { base::badfoo(); } // compile error //void worsebar() { base::nonexist(); } // compile error }; int main() { return 0; }
but commented out lines won't compile.
my questions are:
why
badbar()
compilesworsebar()
doesn't ?if change
badbar()
static won't compile either, regardless ifbase::badfoo
static or not.does standard should checked in situation ? gcc4.4 refuses compile
badbar()
.
update:
problem 1 has been explained number of answers, seems compilers go mile check overload well, happens gcc 4.4.3 , 4.8.2, not 4.7.2 , 4.9.1.
problem 2: marco a. pointed out, clang won't compile gcc4.9 still pass. however, gcc4.2 , gcc4.4 both reject code, , error complaining "no matching function" rather "calling non-static member without object" in clang. there's seems no conclusive answer question, i'm adding language-lawyer tag daniel frey suggested.
more update:
i think question 2 answer pretty clear now: it's compiler whether adding static declaration change diagnosis. varies compiler compiler , different versions of same compiler. language lawyer didn't show up, i'm going accept daniel frey's answer best explained first question. answers marco a. , hadi brais worth reading.
the standard requires name-lookup happen @ phase 1, when template first parsed. turns badfoo
in badbar
why code compiles. compiler not required overload resolution @ time.
the overload resolution (which happens separate step after name lookup) performed in phase 2 when badbar
instantiated - not case in example. principle can found in
3.4 name lookup [basic.lookup]
1 name lookup rules apply uniformly names (including typedef-names (7.1.3), namespace-names (7.3), , class-names (9.1)) wherever grammar allows such names in context discussed particular rule. name lookup associates use of name declaration (3.1) of name. name lookup shall find unambiguous declaration name (see 10.2). name lookup may associate more 1 declaration name if finds name function name; declarations said form set of overloaded functions (13.1). overload resolution (13.3) takes place after name lookup has succeeded. access rules (clause 11) considered once name lookup , function overload resolution (if applicable) have succeeded. after name lookup, function overload resolution (if applicable) , access checking have succeeded attributes introduced name’s declaration used further in expression processing (clause 5).
(emphasis mine)
i'd therefore compiler(s) correct accept code, although i'm not sure required so.
to see code being rejected, need instantiate badbar
.
Comments
Post a Comment