首页 > 解决方案 > 在编译时生成函数

问题描述

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

标签: c++templatesmetaprogramming

解决方案


有没有办法让它工作?

不是这样。

看看你的 lambda

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

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

不能工作。


推荐阅读