简体   繁体   English

通用C ++函数包装

[英]Generic C++ function wrapping

I am tying to write a simple generic smart pointer template that allows a programmer to apply an arbitrary number of wraps before and after calling some function FUNC() eg If a requirement was to start timer, lock, log_start, FUNC(), log_end, unlock , stop timer 我想写一个简单的通用智能指针模板,该模板允许程序员在调用某些函数FUNC()之前和之后应用任意数量的换行,例如,如果需要启动计时器,lock,log_start,FUNC(),log_end,解锁,停止计时器

Then I would like to be able to write something simple where the programmer supplied 3 types and a function to a template and let the compiler do the rest. 然后,我希望能够编写简单的东西,其中程序员为模板提供了3种类型和一个函数,并让编译器完成了其余工作。 I get the feeling it can be done using variadic templates in a manner similar to how typelists worked combined with overloading operator -> 我感觉可以使用可变参数模板以类似于类型列表与重载运算符结合的方式进行操作->

ie

class timer {}; // ctor start timer, dtor stop timer
class locker{}; // ctor lock, dtor unlock
class logger{}; // ctor lock, dtor unlock

Then some code such as 然后是一些代码,例如

template <typename ...base_class_list> 
class aggregate : public base_class_list... {};
using pre_conditions = aggregate<logger, locker, trans>;

class gadget 
{
    auto do_something() -> void;
}; // gadget

Finally (the part I would like to write but don't know how to glue it together 最后(我想写但不知道如何将其粘合在一起的部分

SMART_PTR<pre_conditions, gadget> g;
g->do_something();

I can get it working easily enough using the approach described by Bjarne Stroustrup in “Wrapping C++ Member Function Calls”, but was wondering if there was a more generic and elegant solution. 使用Bjarne Stroustrup在“包装C ++成员函数调用”中描述的方法,我可以使它足够容易地工作,但是我想知道是否有一个更通用,更优雅的解决方案。

The easy way is to wrapping only all operator() : 最简单的方法是只包装所有operator()

template <typename T, typename ... Ts>
struct magic
{
    T obj;

    template <typename ... Us>
    decltype(auto) operator ()(Us...args)
    {
        ordered_tuple<Ts...> t; // tuple doesn't guaranty order
        obj(std::forward<Us>(args)...);
    }
};

Demo 演示版

To wrap operator -> , it is more tricky: 要包装operator -> ,则比较棘手:

template <typename T, typename ... Ts>
class wrapper
{
    ordered_tuple<Ts...> t; // tuple doesn't guaranty order
    T* obj;
public:
    wrapper(T* obj) : obj(obj) {}

    T* operator ->()
    {
        return obj;
    }
};

template <typename T, typename ... Ts>
class magic
{
    T obj;
public:
    wrapper<T, Ts...> operator ->()
    {
        return {&obj};
    }
};

Demo 演示版

Handling const and non-default constructor should also be done. 处理const和非默认构造函数也应该完成。 (and finding better name). (并找到更好的名字)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM