C++ 编译器不检查模板类中是否存在方法

标签 c++ templates definition-checking

我在 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/

相关文章:

c++ - 对于英语单词来说,什么是好的哈希函数?

c++ - Statfs 返回奇怪的值

c++ - VS2017 属性表排序

c++ - 无法将字段声明为嵌套模板中的抽象类型

c++ - 将数组与可变参数模板相关联

c++模板类型推导在强制转换运算符中失败

c++ - 简单模板推导错误

c++模板怪异优化

c++ - 如果方法不进行类型检查,为什么 C++ 模板会匹配?