Have a look at this code:
struct foo {
virtual int bleh() {
return 42;
}
};
template<typename T>
struct bar : public foo {
};
// ERROR
template<>
int bar<char>::bleh() {
return 12;
}
I'm trying to provide a definition of base::bleh
only for bar<char>
, but the compiler(gcc 4.7.2) rejects my code with the following diagnostic:
template-id ‘bleh<>’ for ‘int bar<char>::bleh()’ does not match any template declaration
It seems like base::bleh
is somehow hidden in bar
. I've fixed this using the following definition in bar
:
template<typename T>
struct bar : public foo {
// doesn't work
//using foo::bleh;
// this works
int bleh() {
return foo::bleh();
}
};
But I'm curious as of why this fails to compile. Why is the compiler rejecting my code?
In your non-compiling example, you're attempting to specialize and define a function that hasn't been declared in the template definition of bar
... In your later example you have actually declared as well as defined the non-specialized version of the function inside the template definition of bar
, which is why it compiles. From what I can tell, here is the associated language in the standard concerning why the first version won't compile (14.7.3/4):
A member function, a member function template, a member class, a member enumeration, a member class template, or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall precede the explicit specialization for the member of the class template
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.