Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are members of a class template instantiated when the class is instantiated?

Tags:

c++

c++98

Supposedly members of a template class shouldn't be instantiated unless they are used. However this sample seems to instantiate the do_something member and the enable_if fails (which would be expected if we'd instantiated it - but AFAIK we did not).

Am I missing something really basic here?

#include <string>
#include <boost/utility.hpp>

struct some_policy {
    typedef boost::integral_constant<bool, false> condition;
};

struct other_policy {
    typedef boost::integral_constant<bool, true> condition;
};


template <typename policy>
class test {
   void do_something(typename boost::enable_if<typename policy::condition>::type* = 0) {}
};

int main() {
    test<other_policy> p1;
    test<some_policy>  p2;
}

coliru

like image 722
melak47 Avatar asked Sep 03 '14 12:09

melak47


People also ask

What happens when a class template is instantiated?

Template instantiation involves generating a concrete class or function (instance) for a particular combination of template arguments. For example, the compiler generates a class for Array<int> and a different class for Array<double>.

When the templates are usually instantiated?

The bodies of template classes and inline (or static) template functions are always instantiated implicitly when their definitions are needed. Member functions of template classes are not instantiated until they are used. Other template items can be instantiated by using explicit instantiation.

What is the instantiation of the class template?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.

Does member class require instantiation?

Correct Option: D. The compiler does not generate definitions for functions, non virtual member functions, class or member class because it does not require instantiation.


1 Answers

From C++11 14.7.1/1:

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions

So the function declaration is instantiated; that fails since it depends on an invalid type.

(Unfortunately, I don't have any historic versions of the standard to hand, but I imagine this rule was similar in C++98)

like image 198
Mike Seymour Avatar answered Oct 02 '22 12:10

Mike Seymour