为什么不能从类中的字段推导出模板参数类型?

时间:2020-05-14 19:25:16

标签: c++ templates template-argument-deduction

#include <iostream>
#include <string>

template<typename Func>
class FuncWrapper {
    Func func;
    std::string name;

public:

    FuncWrapper(Func func, std::string name) : func(func), name(std::move(name)) {}

    template<typename ...Args>
    auto operator()(Args ...args) {
        std::cout << "Entering " + name + '\n';
        func(args...);
        std::cout << "Exiting " + name + '\n';
    }
};

template<typename Func>
auto makeFuncWrapper(Func func, std::string name) {
    return FuncWrapper<Func>(func, name);
}

int main() {

    auto helloWorld = []() { std::cout << "Hello World\n"; };
    auto printTwoNums = [](int a, int b) { std::cout << a << ' ' << b << '\n'; };

//    FuncWrapper(helloWorld, "helloWorld")(); // Error.
//    FuncWrapper(printTwoNums, "printTwoNums")(4, 5); // Error.

    makeFuncWrapper(helloWorld, "helloWorld")();
    std::cout << '\n';
    makeFuncWrapper(printTwoNums, "printTwoNums")(4, 5);

}

输出:

Entering helloWorld
Hello World
Exiting helloWorld

Entering printTwoNums
4 5
Exiting printTwoNums

我正在尝试制作一个函数包装器,为该函数添加其他功能。在类FuncWrapper中,存在一个名为func的字段,其字段为模板参数(Func)的类型。当我尝试将lambda传递给构造函数时,出现错误消息,提示我缺少一些模板参数。而如果我使用一个辅助函数,它将正常推断出类型。当我将lambda传递给构造函数时,为什么不能推断出参数的类型?为什么函数可以推断出类的构造函数却不能推断呢?还有什么可能的解决方案?对此代码是否有任何可能的改进,或者实现相同行为的更好方法?

0 个答案:

没有答案