c++ - Error when explicitly converting a template non-type parameter -


consider code:

class base{}; class derived: public base{};  template<base& b> // references (and pointers) can used non-types void f(){}  int main() {     derived d;     // f(d); // error, template type must match     f<(base&)d>(); // error here, why?! } 

i understand why commented call fails: template type must match exactly. try cast in second call, , error (gcc5.2):

error: 'd' not valid template argument type 'base&' because not object external linkage

same error if make derived d; global. clang bit more helpful, saying

... note: candidate template ignored: invalid explicitly-specified argument template parameter 'b'

my question is: code above legal or not? if not, there reasons why?

this answer assumes c++11 or higher

two issues here:

1) no derived-to-base conversion non-type template parameter [temp.arg.nontype]/p1

for non-type template-parameter of reference or pointer type, value of constant expression shall not refer to (or pointer type, shall not address of):

— subobject (1.8),

2) object's address should available @ compile time. summarizing [temp.arg.nontype]/p1 , [expr.const]/p5 follows should have static storage duration.

put these 2 points , you'll have following compiles

class base{}; class derived: public base{};  template<base& b> // references (and pointers) can used non-types void f(){}  base obj; // static storage duration  int main() {     f<obj>(); } 

live example


Comments