什么时候执行类型参数的类型检查?

When is type checking for type argument performed?

这是编程语言实用学中的一些 C++ 模板代码,作者 Scott

template<typename T>
class chooser {
    public:
    virtual bool operator()(const T& a, const T& b) = 0;
};

template<typename T, typename C>
class arbiter {
    T* best_so_far;
    C comp;
public:
    arbiter() { best_so_far = nullptr; }
    void consider(T* t) {
        if (!best_so_far || comp(*t, *best_so_far)) best_so_far = t;
    }
    T* best() {
        return best_so_far;
    }
};

class case_sensitive : chooser<string> {
public:
    bool operator()(const string& a, const string& b) { return a < b; }
};
...
arbiter<string, case_sensitive> cs_names; // declare new arbiter
cs_names.consider(new string("Apple"));
cs_names.consider(new string("aardvark"));
cout << *cs_names.best() << "\n"; // prints "Apple"

the C++ compiler will create a new instance of the arbiter template every time we declare an object (e.g., cs_names) with a different set of generic arguments. Only when we attempt to use such an object (e.g., by calling consider) will it check to see whether the arguments support all the required operations.

Because type checking is delayed until the point of use, there is nothing magic about the chooser class. If we neglected to define it, and then left it out of the header of case_sensitive, the code would still compile and run just fine.

以下两个时间点是编译时还是运行时:

"type checking is delayed until the point of use"是否意味着类型检查在运行时完成?

谢谢。

  • the time "when we attempt to use such an object" and
  • "the point of use"?

两者都指的是源代码,而不是运行时。

这一行:

arbiter<string, case_sensitive> cs_names;

编译器看到 std::stringcase_sensitive,并尝试实现 arbiter 的版本,其中 T 替换为 std::stringC 替换为 case_sensitive.

如果用其他类型定义另一个arbiter,将生成并编译新版本的arbiter

阿兰有权这样做。

为了将来参考 C++,一般来说,编译时会检查所有内容。我所知道的唯一例外是多态类型的动态转换和函数 typeid,returns 对象的类型。

在我看来,如果您曾经使用过这些功能,您通常应该重新考虑您的 O-O 设计。 (或者您正试图在不重构的情况下修复其他人的损坏代码)。