c++ - lambda函数使用其参数作为模板参数调用模板函数

标签 c++ templates metaprogramming

以下是无法编译的示例代码。

我们使用迭代函数在一定范围内进行迭代并运行lambda回调函数。迭代函数会将一些指示(即类型)传递给回调lambda函数,然后该函数将根据指示进行工作。由于这些指示在编译时是固定的,因此我相信有一种方法可以消除运行时的所有指示开销。但是如何..?

template<typename FuncT>
void iterate(const FuncT& func) {
    for(int i = 0; i < 5; ++i)
        func(0, i);
    for(int i = 0; i < 5; ++i)
        func(1, i);
}

template<int d> int getValue(int i) { return d+i; }
// this has run-time overhead compared to the template version
// int getValue(int d, int i) {return d+i; }

int main() {
    iterate([&](const int type, int index){
        // error: cannot compiler here
        // candidate template ignored: invalid explicitly-specified argument for template parameter 'd'
        std::cout<<getValue<type>(index)<<std::endl;
    });
}

最佳答案

您不能将运行时变量用作模板参数,该参数应该是编译时常量。但是您可以将常量包装到 std::integral_constant 中,以将常量值编码为一种类型:

template<typename Func>
void iterate(Func func) {
    for(int i = 0; i < 5; ++i)
        func(std::integral_constant<int, 0>{}, i);
    for(int i = 0; i < 5; ++i)
        func(std::integral_constant<int, 1>{}, i);
}

template<int d>
int getValue(int i) {
    return d + i;
}

int main() {
    iterate([&](auto type, int index) {
        std::cout << getValue<type>(index) << std::endl;
    });
}
std::integral_constant可以隐式转换为基础类型的值。在getValue<type>(index)中,type转换为int类型的包装值。

Demo

关于c++ - lambda函数使用其参数作为模板参数调用模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61796664/

相关文章:

c++ - 具有不同模板参数的模板对象的集合

c++ - 我们可以从 char 指针创建一个 C++ 字符串对象,其中对字符串对象的操作反射(reflect)到源 char 指针吗?

c++ - Boost 进程间在 gcc 4.1.2 上失败

Ruby 元编程

ruby - 元编程多少算太多?

excel - 此时无法进入中断模式错误

c++ - 获取所有正在运行的应用程序(chromium...gedit...等)[C++/Linux]

c++ - opencv 保存从网络摄像头捕获的图像

c++ - boost::lexical_cast 和非内置类型的字符串化

c++ - 查找调用了哪个模板函数重载的规则