【问题标题】:variadic templates: expression list treated as compound expression in functional cast error可变参数模板:表达式列表在功能转换错误中被视为复合表达式
【发布时间】: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


【解决方案1】:

应该是:

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 类中,以便轻松地返回函数的值。

【讨论】:

  • 谢谢!要去调查这个:RAII 和这个Easily measure elapsed time
  • 我也不确定为什么我们需要 std::forward。该资源在哪里提供了帮助Advantages of using forward
  • std::forward 允许使用使用 std::unique_ptr 等类型的函数,(或不带副本的 std::vector)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
相关资源
最近更新 更多