我在 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(); }
};
出于某种原因Val<int>(4).val();
即使没有方法也能正常工作 promote_value()
.我试图删除模板:
class OtherVal {
protected:
int x0, x;
public:
OtherVal (int t = 1) : x0(t), x(1) {}
int val() { return x; }
void promote() { this->promote_value(); }
};
但是现在我得到一个错误:
error: ‘class OtherVal’ has no member named ‘promote_value’; did you mean ‘promote’?
为什么 C++
有这样的行为吗?
最佳答案
模板类方法在使用之前不会被实例化。一旦您尝试调用 promote()
甚至像这样得到它的地址 &Val<int>::promote
那么你会得到一个错误。
来自 C++ 标准:
§ 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.
关于C++ 编译器不检查模板类中是否存在方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891571/