Ell*_*lle 5 c++ inheritance pointers
我试图分析实现多态的各种方法之间的权衡.我需要一个对象列表,它们在成员函数中有一些相似之处和一些差异.我看到的选项如下:
我的理解是,由于成员函数的保证接近,选项3中列表中的指针查找将比选项2的成员函数查找花费更长的时间.
这些选项有哪些优点/缺点?我的首要任务是性能优于可读性.有多态的其他方法吗?
实现更快多态性的一种方法是通过CRTP 惯用法和静态多态性:
template<typename T>
struct base
{
void f()
{
static_cast<T*>( this )->f_impl();
}
};
struct foo : public base<foo>
{
void f_impl()
{
std::cout << "foo!" << std::endl;
}
};
struct bar : public base<bar>
{
void f_impl()
{
std::cout << "bar!" << std::endl;
}
};
struct quux : public base<quux>
{
void f_impl()
{
std::cout << "quux!" << std::endl;
}
};
template<typename T>
void call_f( const base<T>& something )
{
something.f();
}
int main()
{
foo my_foo;
bar my_bar;
quux my_quux;
call_f( my_foo );
call_f( my_bar );
call_f( my_quux );
}
Run Code Online (Sandbox Code Playgroud)
这输出:
噗!
酒吧!
奇怪!
静态多态性比虚拟分派性能好得多,因为编译器知道在编译时将调用哪个函数,并且它可以内联所有内容。
即使它提供动态绑定,它也无法以常见的异构容器方式执行多态性,因为基类的每个实例都是不同的类型。
然而,这可以通过类似的东西来实现boost::any。