在 C++11 上有负责在作用域退出时调用一些成员函数的守卫类:
template <class T, void (T::*op)()>
struct Guard
{
Guard(T*g):
_g(g){}
~Guard()
{
(_g->*op)();
}
T*_g;
};
用法很简单:
typedef Guard<Foo, &Foo::bar> FooGuard;
...
FooGuard g(&foo);
我的问题源自现有的 shared_ptr<Foo>
.如何创建保持 shared_ptr<T>
的特化而不是 T*
我已经尝试过的:
template <class T, void (T::*op)()>
struct Guard<std::shared_ptr<T>, op>
{
Guard(std::shared_ptr<T>& g):
_g(g){}
~Guard()
{
((*_g).*op)();
}
std::shared_ptr<T> _g;
};
但是在 G<std::shared_ptr<Foo>, &Foo::bar> g2(foo);
编译期间可以预见得到:
error C2440: 'specialization' : cannot convert from 'overloaded-function' to 'void (__thiscall std::shared_ptr::* )(void)'
最佳答案
正如@PiotrSkotnicki 已经指出的那样,您的特化无效。 你可以使用类似下面的东西,但是界面看起来不太好:
template <class T, class U, void (U::*op)()>
struct Guard
{
Guard(T*g):
_g(g){}
~Guard()
{
std::cout << "normal guard" << std::endl;
(_g->*op)();
}
T*_g;
};
template <class T, class U, void (U::*op)()>
struct Guard<std::shared_ptr<T>, U, op>
{
Guard(std::shared_ptr<T>& g):
_g(g){}
~Guard()
{
std::cout << "shared_ptr guard" << std::endl;
((*_g).*op)();
}
std::shared_ptr<T> _g;
};
演示:
struct Foo
{
void bar()
{
std::cout << "Foo::bar()" << std::endl;
}
};
int main()
{
Foo foo;
{
typedef Guard<Foo, Foo, &Foo::bar> FooGuard;
FooGuard g(&foo);
}
std::shared_ptr<Foo> foo_ptr = std::make_shared<Foo>();
{
typedef Guard<std::shared_ptr<Foo>, Foo, &Foo::bar> FooGuard;
FooGuard g(foo_ptr);
}
return 0;
}
输出:
normal guard
Foo::bar()
shared_ptr guard
Foo::bar()
关于c++ - 专门化成员指针模板参数解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368722/