美文网首页
std::reference_wrapper

std::reference_wrapper

作者: help_youself | 来源:发表于2019-05-12 15:46 被阅读0次
#include <iostream>
#include <functional>
#include <stdio.h>
#include <type_traits>
using namespace std;
template<class T>
class PtrWrap{
public:
    PtrWrap(T &p):ptr_(std::addressof(p)){}
    PtrWrap(T&&)=delete;
    void Print(){
        printf("%p\n",ptr_);
    }
  operator T& () const noexcept { return *ptr_; }
  T& get() const noexcept { return *ptr_; }

    template<typename... _Args>
    typename result_of<T&(_Args&&...)>::type
    operator()(_Args&&... __args) const
    {
      return std::__invoke(get(), std::forward<_Args>(__args)...);
    }
private:
T *ptr_;
};
template<class T>
PtrWrap<T> Ref(T&t){
    return PtrWrap<T>(t);
}
void assign_fun(int &r){
    r=20;
}
void func(int a, int b)
{
    cout << "a = " << a <<",";
    cout << "b = " << b << endl;
}
int main(){
    int result=0;
    PtrWrap<int> test(result);
    test.Print();
    assign_fun(Ref(result));
    printf("%d\n",result);
    int x=5, y=7;
    PtrWrap<void(int,int)> f0 = func;
    f0(x,y);
}

[1] C++11中std::reference_wrapper的理解https://blog.csdn.net/guoxiaojie_415/article/details/80031948

相关文章

网友评论

      本文标题:std::reference_wrapper

      本文链接:https://www.haomeiwen.com/subject/uspcaqtx.html