Dea*_*ael 136
有两种方法.
第一个是通过静态为类型结构指定接口:
template <class Derived>
struct base {
void foo() {
static_cast<Derived *>(this)->foo();
};
};
struct my_type : base<my_type> {
void foo(); // required to compile.
};
struct your_type : base<your_type> {
void foo(); // required to compile.
};
Run Code Online (Sandbox Code Playgroud)
第二个是避免使用引用到基础或指针到基础的习惯用法并在编译时进行连接.使用上面的定义,您可以使用如下所示的模板函数:
template <class T> // T is deduced at compile-time
void bar(base<T> & obj) {
obj.foo(); // will do static dispatch
}
struct not_derived_from_base { }; // notice, not derived from base
// ...
my_type my_instance;
your_type your_instance;
not_derived_from_base invalid_instance;
bar(my_instance); // will call my_instance.foo()
bar(your_instance); // will call your_instance.foo()
bar(invalid_instance); // compile error, cannot deduce correct overload
Run Code Online (Sandbox Code Playgroud)
因此,在函数中结合结构/接口定义和编译时类型推导允许您进行静态调度而不是动态调度.这是静态多态的本质.