svv*_*svv 11 c++ operator-overloading c++03
我有自己的智能指针实现,现在我试图解决通过其指针调用成员函数的问题.我没有提供任何类似get()的函数(实际上,我提供了一个operator->,但我不想将它用于此目的).
我的问题是:签名和返回类型应该是什么operator->*样的?
为了完整起见,这里有一个完整的,可编译的,最小的例子,受到本文的重点启发,我已经链接到了,并且随着一个小的使用演示被剥离,以便开始这个:
#include <memory>
#include <iostream>
#include <utility>
// Our example class on which we'll be calling our member function pointer (MFP)
struct Foo {
int bar() {
return 1337;
}
};
// Return value of operator->* that represents a pending member function call
template<typename C, typename MFP>
struct PMFC {
const std::unique_ptr<C> &ptr;
MFP pmf;
PMFC(const std::unique_ptr<C> &pPtr, MFP pPmf) : ptr(pPtr), pmf(pPmf) {}
// the 'decltype' expression evaluates to the return type of ((C*)->*)pmf
decltype((std::declval<C &>().*pmf)()) operator()() {
return (ptr.get()->*pmf)();
}
};
// The actual operator definition is now trivial
template<typename C, typename MFP>
PMFC<C, MFP> operator->*(const std::unique_ptr<C> &ptr, MFP pmf)
{
return PMFC<C, MFP>(ptr, pmf);
}
// And here's how you use it
int main()
{
std::unique_ptr<Foo> pObj(new Foo);
auto (Foo::*pFn)() = &Foo::bar;
std::cout << (pObj->*pFn)() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |