Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compiler does not check if a method exists in template class

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?

like image 356
vesii Avatar asked Jul 04 '19 16:07

vesii


2 Answers

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.

like image 111
r3mus n0x Avatar answered Sep 21 '22 10:09

r3mus n0x


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.

like image 42
Bathsheba Avatar answered Sep 19 '22 10:09

Bathsheba