Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method in template class only for certain template parameters correct

Consider the following template class

template<typename T>
struct Caller {
    void func(const T &t) { t.func(); }
    void gunc(const T &t) { t.gunc(); }
};

Now let some class Target only provide the member function func() but not gunc(), i.e.

struct Target {
    void func() const { /* ... /* }
};

is the template instantiation Caller<Target> valid?

GCC, clang as well as VC++ accept such template instantiations. Of course, calling Caller<Target>::gunc() leads to an error but Caller<Target>::func() works just fine and as intended.

Now the question: What is the background for this permissive behavior and where are the relevant paragraphs in C++ standard.

like image 877
phlipsy Avatar asked May 22 '26 18:05

phlipsy


1 Answers

It's specified in the standard, under Templates (14), Template instantiation and specialization (14.7), Implicit instantiation (14.7.1).

3 Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist.

And

11 An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation.

like image 74
Dutow Avatar answered May 28 '26 12:05

Dutow