在编译时生成函数

时间:2018-11-12 21:08:00

标签: c++ templates metaprogramming

我正在尝试使用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(这是不可能的,因为它是一个函数参数)。有办法使它起作用吗?

1 个答案:

答案 0 :(得分:-1)

  

有没有办法使它起作用?

不是这样。

看看你的λ

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

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

不能工作。

相关问题