gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:29:04 25 4
gpt4 key购买 nike

这是来自 Scott 的 Programming Language Pragmatics 的一些 C++ 模板代码

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.

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

  • “当我们尝试使用此类对象时”的时间和

  • “使用点”?

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

谢谢。

最佳答案

  • 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++ - 什么时候执行类型参数的类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46002465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com