Why does the compiler try to instantiate a template that I don't actually instantiate anywhere?

守給你的承諾、 提交于 2019-12-05 00:43:54

It seems to be a Bug (if there is not special flag set as mentioned below). Following is an excerpt from Oracle website for C++ templates:

7.2.2

The ISO C++ Standard permits developers to write template classes for which all members may not be legal with a given template argument. As long as the illegal members are not instantiated, the program is still well formed. The ISO C++ Standard Library uses this technique. However, the -template=wholeclass option instantiates all members, and hence cannot be used with such template classes when instantiated with the problematic template arguments.

I think you stumbled upon a bug related to premature instantiation when compiler sees decltype

template<class T>
struct other_traits; // <-- I don't see a "type" attribute in this struct

template<class T>
struct some_traits{
    typedef decltype(&T::operator()) Fty;
    typedef typename other_traits<Fty>::type type; // <-- Here you are trying to access other_traits<T>::type which doesn't exist
};

int main(){
}

You're making one assumption here, that's technically incorrect. let's tackle that first.

You assume that a syntax error means that a template is instantiated. That's not how templates should be compiled. A template is first compiled before instantiation. This is the phase in which non-dependent names are looked up. Syntax errors can certainly be found in this phase. For instance, anything that's necessarily a declaration regardless of template arguments must end with a ;.

Now the correct question is whether the compiler is correct in considering the specializations of other_traits<T>. There are of course no such specializations by line 9, even though there might be specializations later. But would be the relevant point of instantiation for those? I'd have to look that up (sorry, AFS Away From Standardother_traits<T> would be line 9, then there are no specializations, and other_traits<Fty>::type is invalid. If the point of instantiation for other_traits<Fty>::type would be the same as the point of instantiation for some_traits<T>, i.e. none, then other_traits<Fty>::type should be accepted in phase 1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!