C ++静态而不是动态多态性 [英] C++ static rather than dynamic polymorphism
问题描述
我正在尝试构建一个通用的算法。到目前为止,我已经使用类层次结构和指针,如下例所示:
I'm trying to build a generic algorithm. So far I have achieved this using class hierarchy and pointers, as in the example below:
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);}
};
此设置执行如下:
int main(){
std::unique_ptr<Derived> ptr(new Derived(5.4));
algo(3.2,ptr);
method(2.4);
return 0;
}
这是一个非常简单的例子, 。从我的理解,使用派生类这种方式意味着该方法是在运行时选择而不是在编译时选择。由于我不需要我的算法的任何动态行为 - 一切都在编译时确定 - 这是一个不必要的效率损失。有没有办法在编译时做上面的,即静态多态?
This is a very simple example, of course, but it serves for my question. From what I understand, using derived classes in this way means that the method is chosen at run-time rather than at compile time. Since I do not need any dynamic behaviour from my algorithm - everything is determined at compile time - this is a needless loss of efficiency. Is there a way to do the above at compile time, i.e. static polymorphism?
根据我的理解,只能使用模板获得静态多态性。我还没有能够找到一个具有非原始类型的实现模板。如上面的例子,我需要非默认构造函数的派生类,这似乎不可能...任何人都可以提供任何解决方案,如何这可以做?
From what I understand, it's only possible to get static polymorphism using templates. I haven't been able to find a implement templates with non-primitive types, however. As in the example above, I need derived classes with non-default constructors, which doesn't seem to be possible... Could anyone offer any solutions as to how this might be done?
推荐答案
你的Base类和Derived似乎表示一个只有一个成员函数
的函数,所以我们很可能完全取消多态性,函数转换为算法:
Your Base class and Derived seem to represent a function only having a single member function, so we could most likely do away with the polymorphism completely and pass a function into algo:
#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;
}
这篇关于C ++静态而不是动态多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!