Template class with invalid member functions

限于喜欢 提交于 2019-12-06 04:28:28

Yes, in general. Non-virtual member functions of class templates are themselves function templates, and like all function templates they only get instantiated when used. So if you never use some member function of a class template specialization, member function need not be valid for that specialization.

Since C++11, the standard library actually makes ample use of this fine-grained instantiation control. Type requirements for containers apply to member functions, not to the entire template, so for example you can have an std::map<K, T> where T is not default-constructible; you just cannot call operator[] on it.

Note that explicit class template instantiation instantiates all the member functions.

This is standard behavior and will not change.

The reason is the following: Templates are generic code that needs to work with various type arguments. Some operations in templated code may be perfectly valid for one type (as call_f on A), but horribly wrong for another (as call_f on B). The decision made in the standard was to allow non-sensical template code, such as the call_f for type B, as long as this template function is never used (which would trigger compilation of the template function).

That way, code can be generic and also safe, because these checks are done at compile time.

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