如何使用可变参数模板编写通用函数包装器

How to write a generalized function wrapper using variadic templates

我刚刚开始沉迷于模板的高级使用。我正在尝试为函数编写一个通用的包装器,以包装可能导致异常的函数。如果没有异常发生,包装函数应该将实际的 return 值写入某个引用,然后 return true。如果发生异常,则仅 returns false.

代码

#include <string>
#include <iostream>
#include <functional>
#include <exception>
#include <iomanip>

template<typename TReturn, typename ... TArgs>
bool Try(std::function<TReturn(TArgs...)> &function, typename std::function<TReturn(TArgs...)>::result_type& res, TArgs&...args) {
    try {
        res = function(std::forward<TArgs>(args)...);

        return true;
    }
    catch (...) {
        return false;
    }
}

std::string foo(int val) {
    if (val == 0) {
        throw std::exception();
    }

    return "result";
}

int main() {
    std::string res = "noResult";

    //Should be "false=>noResult"
    std::cout << std::boolalpha << Try(foo, res, 0) << "=>" << res;

    //Should be "true=>result"
    std::cout << std::boolalpha << Try(foo, res, 1) << "=>" << res;
}

预期

我期待像 bool Try(std::function<std::string(int)>& function, std::string& res, int&arg);

这样的模板实例化

相反,它甚至不编译:

错误:

no instance of function template "Try" matches the argument list

'bool Try(std::function<_Ret(_Types...)>,std::function<_Ret(_Types...)>::result_type &,TArgs &...)': could not deduce template argument for 'std::function<_Ret(_Types...)>' from 'std::string (int)'

我想我调用 Try 的方式也可能有缺陷。


我找到了 但我无法使用 return 类型。

是的,对于 return void.

的函数,需要一个特殊的重载


我错过了什么,怎么办?提前致谢!

为什么这么多std::function

template<typename TReturn, typename ... TArgs>
bool Try(TReturn (&function)(TArgs...), TReturn& res, TArgs...args) {
    try {
        res = function(std::forward<TArgs>(args)...);

        return true;
    }
    catch (...) {
        return false;
    }
}

此外,您不能将 0 之类的参数作为参考 TArgs&... 传递。按原样传递它们。