I came across with the following program in C++
:
template <class T>
class Val {
protected:
T x0, x;
public:
Val(T t = 1) : x0(t), x(1) {}
T val() { return x; }
void promote() { this->promote_value(); }
};
For some reason Val<int>(4).val();
works fine even though there is no method promote_value()
. I tried to remove the templates:
class OtherVal {
protected:
int x0, x;
public:
OtherVal (int t = 1) : x0(t), x(1) {}
int val() { return x; }
void promote() { this->promote_value(); }
};
But now I get an error:
error: ‘class OtherVal’ has no member named ‘promote_value’; did you mean ‘promote’?
Why does C++
behave like this?
Template class methods are not instantiated until they are used. Once you try calling promote()
or even get its address like this &Val<int>::promote
then you'll get an error.
From the C++ standard:
§ 17.8.1.10 An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement (9.4.1), unless such instantiation is required.
Templates have always worked this way, principally to facilitate their use.
Because Val<int>(4).val();
doesn't call promote
, that function is not compiled for your particular instantiation of that template so the compiler does not issue a diagnostic.
Many metaprogramming techniques depend on this behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With