【问题标题】:generating functions at compile time在编译时生成函数
【发布时间】:2018-11-12 21:08:00
【问题描述】:

我正在尝试使用 boost hana 在编译时生成函数。这是我写的代码

#include <boost/hana/transform.hpp>

#include <array>

template<int i>
double f(double x)
{
    return x * i; 
}

int main()
{
    constexpr std::array arr = {1,5,10,100,500};

    constexpr auto functions = hana::transform(arr, 
        [](const int a) -> double (*)(double)
        {
            return f<a>;
        }
    );

}

编译时出现 f 不能转换为 double (*)(double) 类型的错误。

我认为问题在于 a 不是 constexpr(这是不可能的,因为它是一个函数参数)。有没有办法让它工作?

【问题讨论】:

  • 不,没有办法用运行时值实例化模板。
  • 但是数组在编译时是已知的...
  • 如果你写了一个constexpr 函数并使用它而不是你的lambda,那会很有趣。这可能有效(我不知道 constexpr 愿意反省多远)。 Aslo 是hana::transform constexpr?可能不会……
  • @galik - “这可能行得通” - 你试过了吗?如果a 值(用于f&lt;a&gt; 的值)通过模板参数传递,则应该可以工作,constexpr 或不constexpr。但是,如果 a 作为普通参数传递,则在 constexpr 函数内也不应该起作用,因为 constexpr 函数也可以在运行时调用。
  • Lambdas 也可以是 constexpr 所以这没有区别

标签: c++ templates metaprogramming


【解决方案1】:

有没有办法让它工作?

不是这样的。

看看你的 lambda

    [](const int a) -> double (*)(double)
    {
        return f<a>;
    }

您正在使用参数a,它在 lambda 中可能是已知的运行时,作为模板参数,必须是已知的编译类型。

不能工作。

【讨论】:

  • @user3726947 - 我看不到std::array 的方法。如果您使用std::integer_sequence,对您有好处; std::integer_sequence&lt;int, 1, 5, 10, 100, 500&gt;?
猜你喜欢
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
相关资源
最近更新 更多