c++ - 专门化成员指针模板参数解析

标签 c++ templates c++11

在 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()

live example

关于c++ - 专门化成员指针模板参数解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368722/

相关文章:

c++ - 将 typedef 作为类的非静态成员访问?

c++ - 如何访问列表中的数据成员,其类型与我的列表不同

c++ - std::function 的开销

c++ - 在 C++ 模板中将变量作为参数传递

c++ - 为什么不从临时对象(operator+ 的结果)中移动不调用构造函数?

c++ - 是否可以获取可变参数函数的参数数量?

c++ - 如何在 Visual Studio 中组织 C++ 大型项目

c++ - 递归类型或依赖上下文过于复杂

java - 将 javadoc 插入现有方法的 Eclipse 模板

php - 哪些模板语言适用于 JS 和 PHP?