gpt4 book ai didi

c++ - 如何避免使用参数相关查找显式特化模板化函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:49 26 4
gpt4 key购买 nike

所以 I've written an answer它使用模板化函数来选择对象类型。

我已经定义了类型:

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 时:

minimizator_weighted ? foo<data_set::pt_weighted>() : foo<data_set::pt>();

Richard Hodges is suggesting使用 Argument Dependent Lookup (ADL)避免“明确专门化的模板功能”。我只是不确定他的意思,所以我想我会提出一个新问题,以便他或其他人可以在答案中进一步解释。

最佳答案

类似的东西。

请注意,我现在可以添加一个新的点类型(或集合类型)而无需更改多个函数中的逻辑。我所要做的就是为新类型提供 operator>>do_something 的 ADL 重载。

所以我的核心逻辑现在和每个集合类型/点类型的实现细节分离了。如果我想在其他坐标系统中使用相同的代码点,我需要更改的代码更少(在实际项目中)。

#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());
}
};

关于c++ - 如何避免使用参数相关查找显式特化模板化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41128744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com