j*******e 发帖数: 674 | 1 By looking at the following code, I am confused by line 3.
Line 3 is not a special case of the base template, it is more like a "class
overload".But it can be compiled successfully.
The obj1 in line 7 is defined acorrding to line 3, but failed to compile.
How come?
=========================
template class Bar{}; //Base template
template class Bar{}; // Specialization, which is good
template class Bar{}; // Also good, how come?
void func(){};
int main(){
//Bar obj1; // Error, from line 3
} | a**a 发帖数: 416 | 2 I think the template specializations are there for trail from the compiler:
compiler is trying for fit your instantiation of a template class
declaration for the most suitable specialization without compilation error.
So if you are trying to instantiate Bar<1, func>, the compiler will find
case 2 instead of case 3 for you. The error for case 3 will be suppressed
silently unless the compiler could not find a fit for you. | h********n 发帖数: 1671 | 3 试了一下,在gcc中直接写进一个常数时会报错
template class Bar{};
但是用T代替1时就不会报错,虽然编译器此时应知道T是一个整数。
这可能是compiler的一个bug,在进行模板参数检查时漏掉了一个case,没能认出T的类
型。模板声明时只进行最基本的检查,可能会漏掉一些错误。如果没有真正用到,这些
错误不会造成任何问题。如果真正用到了,那时更详细的检查就会发现错误。 | j*******e 发帖数: 674 | 4 Thanks for the replies.
I also posted at stackoverflow.com. Their answer is:
The template is not instantiated, so the compiler has the option to report
an error or not. A guy was saying this is actually a very useful feature. |
|