3

Referring to cppreference's section on function templates:

Explicit instantiation of a function template or of a member function of a class template cannot use inline or constexpr

These topics, inline and constexpr, seem separate and unrelated. Why does this restriction exist?

Barry
  • 286,269
  • 29
  • 621
  • 977
lsbbo
  • 304
  • 3
  • 12
  • Because both `inline` and `constexpr` can lead to there not being an actual *instance* of the function? Which of course goes against the whole "explicit *instantiation*" part. – Some programmer dude Feb 02 '17 at 14:42

1 Answers1

3

Because they serve opposite purposes.

The point of explicit instantiation is, in a source file, to provide definitions for templates that your project needs so that you don't have to fully define the template in your header file.

The point of inline is to allow function definitions in a header - so that multiple definitions of the function across multiple translation units can be collapsed into one.

constexpr functions must have definitions visible for the compiler to actually be able to invoke them at compile-time. There is no link-time constexpr.

It doesn't make sense to explicitly instantiate an inline or constexpr function - those function templates must already be defined in header files and so will be able to be implicitly instantiation on-demand.

Community
  • 1
  • 1
Barry
  • 286,269
  • 29
  • 621
  • 977
  • It just occurred to me that some users may also use explicit instantiations as a way to restrict the set of valid instantiations. That is something you might also want to do with `inline` or `constexpr` templates, but explicit instantiations have no effect on program semantics there. – user2023370 Aug 03 '22 at 11:45