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

标签 c++ variadic-templates

我刚刚开始沉迷于模板的高级使用。我正在尝试为函数编写一个通用的包装器,以包装可能导致异常的函数。如果没有异常发生,包装函数应该将实际返回值写入某个引用,然后返回 true .如果发生异常,它只返回 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的方式也可能有缺陷。


我找到了 this simliar question但我无法让它与返回类型一起使用。

是的,对于返回 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&...。只需按原样传递即可。

关于c++ - 如何使用可变参数模板编写通用函数包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582050/

相关文章:

c++ - 从 Typelist 子集创建函数指针

c++ - 可变参数模板参数

c++ - 确定如何定义类型

c++ - 代码::阻止链接错误

c++ - 在包含处理程序的类被破坏后,Asio 调用处理程序

c++ - MS Visual Studio 2017 上的 Variadic 模板编译问题

c++ - 不明确的模板函数重载接受可调用或值 T

c++ - 找不到命令时出现段错误

c++ - 将指针地址从二维数组转移到结构

c++ - 嵌套类中的可变参数模板