【发布时间】:2017-07-04 18:28:55
【问题描述】:
当使用 template style 固有的编译时鸭子类型时,有没有办法强制要求模板参数实现具有特定签名的特定方法?
struct ProtocolT {
void g() const;
void h();
}
// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
x.g();
}
当然,即使没有这个,也有完美的类型安全性:如果模板参数T没有在模板函数实现中使用的方法,编译器总是会报错。
但我发现明确指出class T 必须具有某些class ProtocolT 中指定的所有方法很有吸引力。通过要求 T 中我尚未在模板函数实现中使用的方法,这将允许我在开发过程的早期约束设计。
即使我没有在ProtocolT 中包含任何未使用的方法,我仍然认为当我需要编写一个可用作T 的类时,经过验证的协议一致性会有所帮助。 (当然,没有人阻止我写 ProtocolT 用于文档目的,但是编译器不会验证 ProtocolT 至少包含所有必需的方法。)
【问题讨论】:
-
从
ProtocolT继承以强制实施,然后 SFINAE 输出T。
标签: c++ templates generic-programming type-constraints