5

我了解使用可变参数模板参数的递归性质和特定模板实例化来逐个“吃”参数列表的基本概念。

我知道可以编写 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;
}

科利鲁:http ://coliru.stacked-crooked.com/a/5df2919ccf9e99a6

我在这里在概念上缺少什么?其他答案可能会从表面上简洁地回答这个问题,但我正在寻找一个解释,为什么这个答案让我无法思考。如果我知道我需要using F::operator()继承运算符并且我正确声明返回类型和参数类型不同,那么我还需要做什么才能使其工作?

这是我的思路:

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

1 回答 1

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();
};
于 2015-05-18T06:32:13.103 回答