When is type checking for type argument performed?

浪子不回头ぞ 提交于 2019-12-24 09:48:32

问题


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.


回答1:


  • 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.




回答2:


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).



来源:https://stackoverflow.com/questions/46002465/when-is-type-checking-for-type-argument-performed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!