C++ 基于变量输入的泛型类方法计算
我大致得到了以下设置:C++ 基于变量输入的泛型类方法计算,c++,design-patterns,generic-programming,C++,Design Patterns,Generic Programming,我大致得到了以下设置: #include <iostream> using namespace std; template<typename T> class Element{ T getX() const; T getY() const; private: T x,y; std::vector<float> handling_times; float cost; }; template<typename T
#include <iostream>
using namespace std;
template<typename T>
class Element{
T getX() const;
T getY() const;
private:
T x,y;
std::vector<float> handling_times;
float cost;
};
template<typename T, typename Tnext>
class Bloc {
T getX() const;
T getY() const;
private:
T x,y;
Tnext num_blocs;
float effort;
float damage_done;
};
template<typename T>
class Measurements {
void calcMeasurements(const std::vector<T*> &data);
float getMean() const;
private:
float mean;
};
int main() {
std::vector<Element<int>*> elements;
// fill with elements
std::vector<Bloc<float,2>*> blocs;
// fill with blocs
// calculate mean of blocs effort
Measurements<Bloc<float,1>> bloc_mean_effort_measurement;
bloc_mean_effort_measurement.calcMeasurements(blocs);
return 0;
}
#包括
使用名称空间std;
模板
类元素{
T getX()常数;
T getY()常数;
私人:
tx,y;
std::向量处理时间;
浮动成本;
};
模板
阶级集团{
T getX()常数;
T getY()常数;
私人:
tx,y;
Tnext num_集团;
浮力;
浮子损坏;
};
模板
等级测量{
无效计算测量(常数标准::矢量和数据);
float getMean()常量;
私人:
浮动平均值;
};
int main(){
std::向量元素;
//充满元素
std::向量群;
//充满集团
//计算集团努力的平均值
测量集团(mean)(努力)(measures)(measures)测量;;
集体平均努力测量。计算测量(集体);
返回0;
}
所以有两个类
Element
和Bloc
,它们保存了一些数据,我想对这些数据执行测量。例如,我想测量元素的处理时间的getMean()
,其类型为std::vector
。另一种情况是根据存储在每个Bloc
中的努力来测量std::vector Bloc
的平均值。正如您所见,测量的输入类型有所不同,但平均值计算背后的功能始终保持不变。我希望这个功能只实现一次(mean只是我能想到的最简单的例子),并在不同的类型上使用它。此外,我还无法了解如何根据哪个实体(例如,元素
成本
或集团
努力
)计算度量值。在元素
中使用处理时间
和成本
的枚举可能的度量值
有意义吗。也就是说,对于每个私有变量,我希望能够计算度量 如果我正确理解了这个问题,你或多或少会有这样的想法:
struct A {
std::vector<int> a;
};
struct B {
int value;
B(int x) : value(x) {}
};
typedef std::vector<B> Bvect;
您必须传递两个迭代器,指示要累加的第一个和最后一个元素之后的一个迭代器,以及一个初始值
对于Bvect
,它看起来非常相似,我们只需提供一种自定义的元素相加方法:
Bvect b;
b.push_back(B(123));
std::cout << std::accumulate(b.begin(),
b.end(),
B(0),
[](B b1,B b2){
return B(b1.value + b2.value);
}).value << "\n";
Bvect b;
b、 推回(b(123));
标准::cout
Bvect b;
b.push_back(B(123));
std::cout << std::accumulate(b.begin(),
b.end(),
B(0),
[](B b1,B b2){
return B(b1.value + b2.value);
}).value << "\n";