【发布时间】:2019-01-09 18:48:23
【问题描述】:
我尝试将函数作为参数传递,并将参数包作为第二个参数传递给包装函数。
在这种简单的情况下,包装函数应该执行传入的函数,并带有包中的参数,测量执行时间并退出。
但我在 Ubuntu 18.04 上使用 g++ 7.3.0 (c++14) 时出现编译错误:
error: expression list treated as compound expression in functional cast [-fpermissive]
换行:
func(&args...);
包装如下:
template<typename func, typename ...Types>
void measure_time(func, Types... args)
{
auto start = std::chrono::system_clock::now();
// execute function here
func(&args...);
auto end = std::chrono::system_clock::now();
std::cout << "Time for execution "
<< std::chrono::duration_cast<std::chrono::microseconds>(end-start).count()
<< " microseconds\n";
}
我是通用编程和参数包的新手,但遵循 parameter packs 的 cpp 参考应该可以吗?
调用 measure_time 函数,例如使用简单的 binary_search:
int binary_search(int *a, int v, int l, int r)
{
while(r >= 1)
{
int m = (l+r)/2;
if(v == a[m]) return m;
if(v < a[m]) r = m-1; else l = m+1;
if(l==m || r==m) break;
}
return -1;
}
产生以下实例化(对我来说似乎是正确的)作为错误源:
In instantiation of ‘void measure_time(func, Types ...) [with func = int (*)(int*, int, int, int); Types = {int*, int, int, int}]’:
我发现这篇文章描述了一个编译器错误,但我缺乏了解这种情况的知识,并且在这种情况下似乎无法推断出可行的解决方案: temporary objects with variadic template arguments; another g++/clang++ difference
编辑:使用 -fpermissive 标志运行程序,然后执行程序完美无缺。
【问题讨论】:
-
func是一个类型,而不是一个变量。
标签: c++ parameter-passing variadic-templates