Pla*_*men 5 c++ templates static-polymorphism
我正在尝试构建一个通用算法.到目前为止,我已经使用类层次结构和指针实现了这一点,如下例所示:
struct Base{
virtual double fn(double x){return 0;}
};
class Derived : public Base{
double A;
public:
Derived(double a) : A(a) {}
double fn(double x) { return A*x;}
};
//Some other implementations
class algo{
double T;
std::unique_ptr<Base> b_ptr;
public:
algo(double t, std::unique_ptr<Base>& _ptr); //move constructor...
//Some constructors
double method(double x){ return T*b_ptr->fn(x);}
};
Run Code Online (Sandbox Code Playgroud)
然后按如下方式实现此设置:
int main(){
std::unique_ptr<Derived> ptr(new Derived(5.4));
algo(3.2,ptr);
method(2.4);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,这是一个非常简单的例子,但它适用于我的问题.据我所知,以这种方式使用派生类意味着该方法是在运行时而不是在编译时选择的.因为我的算法不需要任何动态行为 - 所有内容都是在编译时确定的 - 这是一种不必要的效率损失.有没有办法在编译时执行上述操作,即静态多态?
据我所知,只有使用模板才能获得静态多态性.但是,我无法找到具有非基本类型的工具模板.如上例所示,我需要使用非默认构造函数的派生类,这似乎不可能......任何人都可以提供任何解决方案来解决这个问题吗?
您的基类和派生类似乎表示一个仅具有单个成员函数的函数,因此我们很可能完全消除多态性并将函数传递给算法:
#include <iostream>
#include <utility>
template <class Function>
class algo
{
double t;
Function fn;
public:
algo(double t, const Function& fn)
: t{t}, fn{fn}
{ }
double method(double x){ return t * fn(x);}
};
template <class Function>
algo<Function> make_algo(double t, Function&& fn)
{
return algo<Function>(t, std::forward<Function>(fn));
}
int main()
{
const double someValue = 123;
const double anotherValue = 987;
auto algo = make_algo(anotherValue, [someValue](double otherValue) {
return someValue * otherValue;
});
std::cout << std::fixed << algo.method(321) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1813 次 |
| 最近记录: |