When is type checking for type argument performed?

2019-08-11 16:24发布

Here is some C++ template code from Programming Language Pragmatics, by 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.

Are the following two time points at compile time or run time:

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

  • "the point of use"?

Does "type checking is delayed until the point of use" mean that the type checking is done at runtime?

Thanks.

2条回答
Emotional °昔
2楼-- · 2019-08-11 16:44

Alain has the right of it.

For future reference C++, in general, compile-time checks everything. The only exceptions I know of are dynamic casting of polymorphic types and the function typeid, which returns the type of an object.

In my opinion if you are ever using those functions you should usually rethink your O-O design. (or you are trying to fix someone else's broken code without refactoring).

查看更多
霸刀☆藐视天下
3楼-- · 2019-08-11 16:48
  • the time "when we attempt to use such an object" and
  • "the point of use"?

Both refer to the source code, not to runtime.

In this line:

arbiter<string, case_sensitive> cs_names;

the compiler sees a std::string and case_sensitive, and tries to implement a version of arbiter with T replaced by std::string and C replaced by case_sensitive.

If you define another arbiter with other types, a new version of arbiter will be generated and compiled.

查看更多
登录 后发表回答