c++ - 可变参数模板 : expression list treated as compound expression in functional cast error

标签 c++ parameter-passing variadic-templates

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

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

但我在 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/

相关文章:

c++ - 指向可变函数模板的指针

c++ - 可变参数模板仅在前向声明时编译

c++ - Foundation framework和XCode8.0编译报错

c++ - Boost - 在图中查找最大匹配边

C++ 线程安全 - map 读取

java - 在 Java 中传递抽象类

c++ - 将抽象 C++ 类传递给构造函数并调用成员方法

jquery - 传递给 J 查询 token 输入的附加参数

c++ - 为什么将 double 类型转换为 int 似乎会在第 16 位数字后四舍五入?

c++ - 单例,奇怪的重复模板模式和转发构造函数参数