So 我已经写了一个答案 https://stackoverflow.com/a/41125514/2642059它使用模板化函数来选择对象类型。
我已经定义了类型:
struct pt {
double t;
double e;
double c_vis;
double c_invis;
};
struct pt_weighted : pt {
double sigma;
};
我的模板化函数如下所示:
template <typename T>
void foo() {
for(T point; dataFile >> point;) {
set.curve.push_back(point); // store point
data_numPoints++; // collect some stats
set.curveAvg += point.e;
}
}
鉴于minimizator_weighted
决定在运行时使用哪种类型,我称之为foo
with:
minimizator_weighted ? foo<data_set::pt_weighted>() : foo<data_set::pt>();
理查德·霍奇斯建议 https://stackoverflow.com/questions/41124382/conditional-line-by-line-reading-from-file/41125514?noredirect=1#comment69460665_41125514 using 参数相关查找 (ADL) http://en.cppreference.com/w/cpp/language/adl以避免“明确专门的模板函数”。我只是不确定他的意思,所以我想我应该提出一个新问题,以便他或某人可以在答案中进一步解释。
沿着这些思路的东西。
请注意,我现在可以添加一种新的点类型(或集合类型),而无需更改多个函数中的逻辑。我所要做的就是提供 ADL 超载operator>>
and do_something
对于新类型。
所以我的核心逻辑现在与每个集合类型/点类型的实现细节分离。如果我想在其他坐标系中使用相同的代码点,则需要更改的代码较少(在实际项目中)。
#include <iostream>
#include <vector>
struct pt {
double t;
double e;
double c_vis;
double c_invis;
};
std::istream& operator>>(std::istream& is, pt& p)
{
p.c_vis = 0;
p.c_invis = 0;
return is >> p.t >> p.e;
}
struct pt_weighted : pt {
double sigma;
};
std::istream& operator>>(std::istream& is, pt_weighted& p)
{
auto sigma_correction = [](double& sigma) {
// whatever this is supposed to do;
};
is >> static_cast<pt&>(p) >> p.sigma;
sigma_correction(p.e);
return is;
}
template<class Point> struct set
{
using point_type = Point; // the type name point_type is now part of the set's type interface, so I can use it in dependent code.
std::vector<point_type> points;
};
using pt_set = set<pt>;
using pt_weighted_set = set<pt_weighted>;
//
// one implementation of read logic, for all set types.
//
template<class SetType>
void read_set(std::istream& is, SetType& target)
{
while(is) {
// using the type protocol here
auto point = typename SetType::point_type(); // or target.makePoint() ?
is >> point;
target.points.push_back(std::move(point));
}
}
extern void do_something(pt_set&);
extern void do_something(pt_weighted_set&);
void operation(std::istream& is)
{
extern bool useSigma();
// even these lines now no longer need to be repeated
auto perform = [](auto&& myset) {
read_set(is, myset);
do_something(myset);
};
if (useSigma())
{
perform(pt_weighted_set());
}
//else if (someOtherCondition()) {
// perform(someOtherSetType());
//}
else {
perform(pt_set());
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)