With the new C++20 standard coming out, there are a number of relaxations in what we can include in a function marked constexpr
(e.g. try-catch blocks) and what functions can be marked constexpr
(e.g. virtual functions). While I understand the usefulness of this, as I've found myself attempting to write try-catch blocks in constexpr functions pre-C++20; it struck me as odd that these inherently runtime procedures could be evaluated at compile-time. As I dug around searching for an explanation, everything seemed to point back to these restrictions being arbitrary.
This got me wondering if it is the same for templates. For example, member function templates can't be virtual as in the following example:
class MyClass
{
public:
template<typename T>
virtual void doSomething(); // Error: 'virtual' is not allowed in a function template declaration
};
So is this restriction just an arbitrary constraint or is there something different between the compile-time evaluations of a constexpr
function and a function template?
Note: I found this question to be helpful in explaining why it would be difficult (impossible??) to allow this, so my question is less about if it's possible and more of why it's easy for compilers to implement with constexpr
and not with templates.