考虑以下函数:
template <int node>
void RemainingEnergyTrace (double oldValue, double newValue)
{
std::stringstream ss;
ss << "Energy_" << node << ".log";
static std::fstream f (ss.str().c_str(), std::ios::out);
f << Simulator::Now().GetSeconds() << " Remaining energy=" << newValue << std::endl;
}
注意函数int node的模板定义。我尝试在 main() 中传递这个函数的地址:
int inc = 0;
eSources.Get (inc)->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback(&RemainingEnergyTrace<inc>));
这会产生以下错误:
error: the value of ‘inc’ is not usable in a constant expression
eSources.Get (inc)->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback(&RemainingEnergyTrace<inc>));
^
error: no matching function for call to ‘MakeCallback(<unresolved overloaded function type>)’
eSources.Get (inc)->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback(&RemainingEnergyTrace<inc>));
^
但是,以下语句有效:
eSources.Get (0)->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback(&RemainingEnergyTrace<0>));
总而言之,实际数字有效,但当以模板格式传递整数变量时,则无效。是否因为整型变量必须是 const 类型(如错误所示)?
我正在尝试实际运行一个循环并传递不同整数值的函数地址。我怎样才能做到这一点?
for(int inc = 0; inc<nWifi; inc++)
{
eSources.Get (inc)->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback(&RemainingEnergyTrace<inc>));
}
最佳答案
简而言之,you can't 。由于模板在编译时扩展,因此您还需要在编译时提供值。如果 nWifi
是仅在运行时可用的值,则需要使用常规参数:
void RemainingEnergyTrace (double oldValue, double newValue, int node);
如果您想创建部分应用函数来传递给您的MakeCallback
,您可以使用 lambda 来创建它们:
for(int inc = 0; inc<nWifi; inc++)
{
auto callback = [=](double oldVal, double newVal) {
RemainingEnergyTrace(oldVal, newVal, inc);
};
...
}
但是这个won't decay to a function pointer ,因此您可能需要将 MakeCallback
API 更改为例如使用 std::function
(这是当今的首选方法)或采用附加参数1,或者使用一些可以提供您所需的委托(delegate)功能的库。
1通常,采用函数指针的 C 或 C++ API 还会采用附加的 void*
参数来与函数指针一起存储。然后,在调用时,指针将传递给该函数,并存储必要的闭包数据(在您的情况下,它可能指向驻留在内存中某处的 inc
值)。如果不知道 MakeCallback
的工作原理,就不可能判断什么是最好的解决方案。
关于c++ - 传递函数模板的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163091/