可变参数模板:表达式列表在功能转换错误中被视为复合表达式

variadic templates: expression list treated as compound expression in functional cast error

我尝试将函数作为参数传递给包装函数,并将参数包作为第二个参数。

在这种简单的情况下,包装函数应该使用包中的参数执行传递的函数,测量执行时间并退出。

但是我在 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}]’:

我发现这篇文章描述了编译器错误,但我缺乏了解情况的知识,如果是这种情况,似乎无法推导出可行的解决方案:

编辑: 运行 带有 -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 class 中,以便让你的函数的 return 值变得容易。