我尝试将函数作为参数传递给包装函数,并将参数包作为第二个参数传递给包装函数。
在这种简单的情况下,包装函数应该使用包中的参数执行传递的函数,测量执行时间并退出。
但我在 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 标志运行程序,然后执行程序完美无缺。
最佳答案
应该是:
template<typename Func, typename ...Types>
void measure_time(Func func, Types&&... args)
{
auto start = std::chrono::system_clock::now();
// execute function here
func(std::forward<Types>(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";
}
但更好的办法是将时间安排在 RAII 类中,以便轻松返回函数的值。
关于c++ - 可变参数模板 : expression list treated as compound expression in functional cast error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108256/