「这是我参与11月更文挑战的第 11 天,活动详情查看:2021最后一次更文挑战」。
参加该活动的第 25 篇文章
正文
所谓 C++11 的静态多态,其实就是编译期多态,是区别于通过派生继承来实现的运行时多态(即动态多态)。
先举一个通过派生来实现(动态)多态的例子
通过派生实现动态(运行时)多态
假设有一个聚合算法接口,通过派生分别实现加法和减法。
具体代码和注释如下所示:
/// @note 定义一个接口
struct IAggregate
{
virtual int Aggregate(int x, int y) = 0; ///< 纯虚函数
};
/// @note 实现接口的派生类 —— 加法
struct Add : public IAggregate
{
int Aggregate(int x, int y)
{
return x + y;
}
};
/// @note 实现接口的派生类 —— 减法
struct Sub : public IAggregate
{
int Aggregate(int x, int y)
{
return x - y;
}
};
void TestAggregate()
{
/// @note 加法
shared_ptr<IAggregate> ptrAdd(new Add);
ptrAdd->Aggregate(3, 4);
/// @note 减法
shared_ptr<IAggregate> ptrSub(new Sub);
ptrSub->Aggregate(3, 4);
}
通过泛型函数实现静态(编译期)多态
前文 C++11 简化代码中的重复逻辑 提到过使用泛型函数来简化代码中(部分行为相同,部分行为不同)的重复逻辑。其实泛型函数还有一个很强大的能力 —— 实现静态(编译期)多态
具体代码和注释如下所示:
/// @note 使用泛型函数 F 实现静态多态
template <typename T, typename F>
auto Aggregate(const T &x, const T &y, F &f) -> decltype(f(x, y))
{
return f(x, y);
}
void TestAggregate()
{
/// @note 实现加法的 lambda 表达式
Aggregate(3, 4, [](int x, int y)
{ return x + y; });
/// @note 实现减法的 lambda 表达式
Aggregate(3, 4, [](int x, int y)
{ return x - y; });
}
总结
我们可以看到通过泛型函数实现多态调用代码更简洁,消除了继承的强耦合,也提高了性能(不用运行时去判断调用哪个函数,编译期就决定了)。