【发布时间】:2015-12-02 19:35:25
【问题描述】:
这是我目前拥有的
void test(int& i, float& f) {}
template <class... Ts, class F>
void update(F&& f)
{
//Use Ts here
}
int main()
{
update<int, float>(test);
}
但我需要使用<int, float> 显式调用更新,因为我想将其用于元编程。
如果可以从函数中自动推导出来就好了
void test(int& i, float& f) {}
template <class... Ts>
void update(std::function<void(Ts&...)> f)
{
//use Ts here
}
int main()
{
//error: no matching function for call to 'update'
update(test);
}
【问题讨论】:
-
boost function traits 或 other function traits 可能会有所帮助。
-
这个问题之前在stackoverflow上已经回答过好几次了。基本上编译器无法提前知道
void(*)(int&, float&)可以转换为std::function<void(int&, float&)>,因为它在推导出Ts...之后才能看到function特化的构造函数,但是没有办法提前推导出来(编译器都知道,std::function的每个特化都可以从该函数指针转换)。