什么时候进行类型参数的类型检查? [英] When is type checking for type argument performed?

查看:121
本文介绍了什么时候进行类型参数的类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是Scott的《编程语言实用语言》中的一些C ++模板代码。

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"




C ++编译器将创建一个新实例每次我们声明带有$ b $的对象(例如 cs_names )时,仲裁者
模板b不同的一组通用参数。 仅当我们尝试使用这样的
对象(例如,通过调用 consider )时,它才会检查
参数是否支持全部

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.

由于类型检查被推迟到使用点,所以
并没有什么神奇的选择器类。如果我们忽略定义它,然后将其保留在 case_sensitive
标头中,则代码
仍然可以编译并仅运行。 / p>

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

使用点的时间? p>

"the point of use"?

类型检查是否延迟到使用点是否意味着类型检查在运行时完成?

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

谢谢。

推荐答案



  • 尝试使用此类对象的时间和

  • 使用点的时间?

两者都引用源代码,而不是运行时。

Both refer to the source code, not to runtime.

在此行:

arbiter<string, case_sensitive> cs_names;

编译器会看到 std :: string case_sensitive ,并尝试使用 T arbiter c>替换为 std :: string ,而 C 替换为 case_sensitive

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.

这篇关于什么时候进行类型参数的类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆