模板函数接受带有X参数的可调用函子 [英] Template function accepting callable functors with X parameters

查看:207
本文介绍了模板函数接受带有X参数的可调用函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个托管的C ++程序,运行用户编写的C代码。绝对重要的是,某些典型的异常从C代码捕获并被处理/忽略。
为此,我从结构化异常处理块中调用C代码。由于这个块的性质和语义(和它从哪里调用),我已经分离了它自己的函数的实际调用:

I'm writing a hosted C++ program that runs user-written C-code compiled on the fly. It's absolutely vital that certain typical exceptions are caught from the C-code and processed/ignored. To do this, I'm calling the C code from within a structured exception handling block. Due to the nature and semantics of this block (and where it's called from), I've separated the actual calling to it's own function:

    template <typename ret_type, class func>
        static ret_type Cstate::RunProtectedCode(func function) {
            ret_type ret = 0;
            __try {
                ret = function();
            }
            __except(ExceptionHandler(GetExceptionCode(), ExceptionStatus::CSubsystem)) {
                fprintf(stderr, "First chance exception in C-code.\n");
            }
            return ret;
        }

它的工作原理很好,因为:

Which works nicely as it should like so:

        RunProtectedCode<int>(entry);

但是它是可能的形状,所以我可以调用函数的变量参数 - 使用异常函数(只需要显然是不能有一个析构函数)?我使用MSVC ++ 2010。

But is it possible to shape this so i can call functions with variable amounts of parameters - maybe through some use of exotic functors (only requirement is obviously that it can't have a destructor)? I'm using MSVC++ 2010.

推荐答案

如果你可以使用C ++ 11你可以使用可变参数tempaltes。 p>

If you can use C++11 you can achive this with variadic tempaltes.

template <typename ret_type, class func, typename... Args>
    static ret_type Cstate::RunProtectedCode(func function, Args... args) {
        ret_type ret = 0;
        __try {
            ret = function(args...);
        }
        __except(ExceptionHandler(GetExceptionCode(), ExceptionStatus::CSubsystem)) {
            fprintf(stderr, "First chance exception in C-code.\n");
        }
        return ret;
    }

您可以像下面这样调用

RunProtectedCode<int>(entry2, 1, 2);
RunProtectedCode<int>(entry3, 1, "a", 3);






)使用std :: function代替。


You can simplify it (kind of) by using std::function instead.

template <class func, typename... Args>
    static 
    typename func::result_type Cstate::RunProtectedCode(func function, Args... args) {
        typename func::result_type ret = typename func::result_type();
        __try {
            ret = function(args...);
        }
        __except(ExceptionHandler(GetExceptionCode(), ExceptionStatus::CSubsystem)) {
            fprintf(stderr, "First chance exception in C-code.\n");
        }
        return ret;
    }

您可以像下面这样调用

std::function<int(int,int,int)> entry_f = entry;
RunProtectedCode(entry_f,1,2,3);

这篇关于模板函数接受带有X参数的可调用函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆