【发布时间】:2016-03-02 22:29:06
【问题描述】:
我想将重载函数应用于结构的所有元素,如下所示:(下面的代码将无法编译)
#include <iostream>
typedef struct {
float float_val;
int int_val;
} NodeStatus;
template<typename T>
void ApplyToFields(NodeStatus *ns1, NodeStatus *ns2, void (*func)(T, T)) {
func(ns1->float_val, ns2->float_val);
func(ns1->int_val, ns2->int_val);
}
template<typename T>
void add_print(T a, T b) {
std::cout << b + a << std::endl;
}
template<typename T>
void sub_print(T a, T b) {
std::cout << b - a << std::endl;
}
int main() {
NodeStatus ns1, ns2;
ns1.float_val = 2.3;
ns2.float_val = 25.3;
ns1.int_val = 2;
ns2.int_val = 20;
ApplyToFields(&ns1, &ns2, add_print);
ApplyToFields(&ns1, &ns2, sub_print);
}
我是来自 C 的 C++ 新手。经过一些研究,我意识到在 C++ 中传递函数指针可能不是正确的方法。我对实现相同目的的最佳方法感兴趣,而不是我提出的可能不可能的字面问题。遵循 C++03 的解决方案将是理想的。谢谢!
【问题讨论】:
标签: c++ function templates pointers