【问题标题】:Unable to compile constexpr function with variadic arguments无法使用可变参数编译 constexpr 函数
【发布时间】:2021-11-28 21:27:13
【问题描述】:

我正在编写带有可变参数的constexpr 乘积函数。我只能在下面获得“版本 1”。尝试编译“版本 2”时,我收到错误声明类型包含未扩展的参数包'data_type'。谁能解释一下为什么会这样?

/** Version 1. */
template <typename data_type, typename ...data_types>
constexpr data_type Product1(data_type _first, data_types ..._rest) // This code compiles :)
{
  return _first*(_rest * ...);
}

/** Version 2. */
template <typename ...data_type>
constexpr data_type Product2(data_type ..._rest) // This code does not compile :(
{
  return (_rest * ...);
}

【问题讨论】:

    标签: c++ templates c++17 variadic-templates variadic-functions


    【解决方案1】:

    将返回类型改为auto,datatype是一个pack,不能作为返回类型

    template <typename ...data_type>
    constexpr auto Product2(const data_type& ..._rest) 
    {
        return (_rest * ...);
    }
    
    int main()
    {
        constexpr auto p = Product2(1, 2, 3);
        return 0;
    }
    

    【讨论】:

    • 太棒了,非常感谢!宇宙秩序已经恢复:D
    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2011-12-08
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    相关资源
    最近更新 更多