【发布时间】:2021-10-29 13:35:07
【问题描述】:
鉴于此代码
struct data {
int velocity;
};
template <typename Data>
class Collector {
// ...
public:
void add(const Data& data) {}
template <typename T>
T average1(T Data::*field) const {
return T{}; // Some calculation here
}
template <T Data::*field>
T average2() const {
return T{}; // Some calculation here
}
};
void foo() {
Collector<data> collector;
// I have no problem handling the average by sending member as parameter
auto ok = collector.average1(&data::velocity);
// But compilation here fails
auto error = collector.average2<&data::velocity>();
}
我的意图是用模板参数替换指向函数的成员指针,但不能同时匹配成员类型和成员,我可以做类似的事情
template <typename T, T Data::*field>
T average2() const {
return T{}; // Some calculation here
}
但是我必须调用 as
auto error = collector.average2<int, &data::velocity>();
那是丑陋的,似乎没有必要
您对如何解决此问题或收集此类数据有更好的方法有什么想法吗?
提前致谢
【问题讨论】:
标签: c++ templates template-matching pointer-to-member