【问题标题】:Can I use the type of "this" as a template argument (inside a macro)?我可以使用“this”的类型作为模板参数(在宏内)吗?
【发布时间】:2011-09-11 23:06:38
【问题描述】:

我目前有这个:

#define THIS(T) (boost::static_pointer_cast<T>(shared_from_this()))

宏被用在这样的方法中:

void Derived::run() {
    do_something_with_a_shared_ptr(THIS(Derived));
}

这一切都很好,但我想删除 (Derived) 并拥有:

void Derived::run() {
    do_something_with_a_shared_ptr(THIS);
}

这可能吗?

或者,在从boost::enable_shared_from_this 派生(间接)的类中,是否有更好的方法可以方便地访问shared_ptrthisThis question 似乎表明答案是否定的。

类层次结构如下所示:

class Base: public boost::enable_shared_from_this<Base> {
    ...
}

class Derived: public Base {
    ...
    void run();
    ...
}

void do_something_with_a_shared_ptr(boost::shared_ptr<Derived>);

【问题讨论】:

    标签: c++ boost shared-ptr


    【解决方案1】:

    不完全是您问题的答案,但您是否考虑过使用成员函数而不是宏?我通常会这样做:

    boost::shared_ptr< Derived > shared_this()
    {
         return boost::static_pointer_cast<Derived>(shared_from_this());
    }
    boost::shared_ptr< Derived const > shared_this() const
    {
         return boost::static_pointer_cast<Derived const>(shared_from_this());
    }
    

    【讨论】:

    • 请注意,如果你使用的是 C++11,你可以根据 decltype 和 this 做一些事情。
    • 阅读 decltype 和 C++11 非常有趣,谢谢。您的答案肯定优于使用宏,但如果我有几个派生类(我这样做),我需要重复此代码。这些方法可以包含在 Derived 继承的另一个类中,但是我们有多重继承。这是要走的路还是可以用模板做其他事情?
    • 您应该能够在Derived 上制作shared_this 模板,在Base 中声明一次,并在每个不同的Derived 类中使用它。
    • 非常好,效果很好。从THIS(Derived) 我现在有了shared_this&lt;Derived&gt;(),感觉更像C++,希望decltype 可以让这更简单。非常感谢,我在这里学到了很多东西。
    • 只是想如果您在 Derived 上模板 shared_this 并将 Derived/Derived const 指针作为参数传递给它,您甚至可以在 C++03 中自动获取类型。导致shared_this( this ); 对您来说可能更好,我宁愿坚持明确说明类型。
    猜你喜欢
    • 1970-01-01
    • 2016-11-17
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多