我还需要使用可变参数模板继承来创建lambda重载吗?

Cin*_*lue 5 c++ lambda templates conceptual-model c++11

我理解使用可变参数模板参数的递归性质和特定模板实例化的基本概念,逐个"吃"我的方式通过参数列表.

我知道lambdas可以编写为采用某些类型然后返回某些类型.请记住,我还在学习C++ 14和C++ 11,所以我还没有掌握其中的一个.

这是我在查看其他 Stack Overflow问题后的尝试:

// For std::string
#include <string>

// For std::cout
#include <iostream>


//Create a generalized list instantiation
template <typename ... F>
struct overload : public F... {
    overload(F... f) : F(f)... {}
};      

//Create an specific end-case, where we directly
//inherit the () operator in order to inherit
//multiple () overloads
template <typename F>
struct overload : F {
    using F::operator();
};


//template function to create an overload
template <class... F>
auto make_overload(F... f) {
    return (f...);
}

int main() {
    auto f = [](int x,int y) -> int {
        return x+y;
    };
    auto g = [](double x,double y) -> int {
        return std::ftoi(x+y);
    };
    auto h = [](std::string x,std::string y) -> int {
        return std::stoi(x+y);
    };

    //Ah, but this is a function.
    auto fgh = make_overload(f,g,h);

    std::cout << (fgh(1,2)) << std::endl;
    std::cout << (fgh(1.5,2.5)) << std::endl;
    std::cout << (fgh("bob","larry")) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Coliru:http://coliru.stacked-crooked.com/a/5df2919ccf9e99a6

我在概念上缺少什么?其他答案可能会以面值简洁地回答这个问题,但我正在寻找一个解释为什么答案不能解释我的想法.如果我理解我需要using F::operator()继承运算符并且我正确地声明返回和参数类型不同,我还需要做些什么来使其工作?

这是我的思路:

  1. 创建一个通用的可变参数模板基类.
  2. 创建一个特定的模板案例来重载特定的lambda operator().
  3. 创建一个辅助函数来获取一个可变参数模板参数列表,然后用它来构造"重载"类.
  4. 确保类型明确无误.

T.C*_*.C. 5

你实际上没有递归。

// primary template; not defined.
template <class... F> struct overload;

// recursive case; inherit from the first and overload<rest...>
template<class F1, class... F>
struct overload<F1, F...> : F1, overload<F...> {
    overload(F1 f1, F... f) : F1(f1), overload<F...>(f...) {}

    // bring all operator()s from the bases into the derived class
    using F1::operator();
    using overload<F...>::operator();
};      

// Base case of recursion
template <class F>
struct overload<F> : F {
    overload(F f) : F(f) {}
    using F::operator();
};
Run Code Online (Sandbox Code Playgroud)

  • @VermillionAzure:它[编译](http://coliru.stacked-crooked.com/a/f1273aa625818808) 修正了错字 (2认同)