宏观和功能中的'this'指针

Max*_*rai 1 c++ macros inline this

我有一些代码使用调用此代码的类的'this'指针.例如:

Some::staticFunction<templateType>(bind(FuncPointer, this, _1));
Run Code Online (Sandbox Code Playgroud)

这是我从boost调用bind函数.但没关系.现在我必须包装此代码.我做了一个宏:

#define DO(Type, Func) Some::staticFunction<Type>(bind(FuncPointer, this, _1));
Run Code Online (Sandbox Code Playgroud)

并且编译器将此代码插入到调用此宏的类中,因此'this'来自调用者.但我不想使用宏和首选功能(内联).但如何解决'这'传递.我可以在内联函数中使用它,如在宏中,或者我必须手动传递它吗?

Joh*_*itb 5

this关键字可以通过调用该函数可以把

class MyClass {
  // ...
  template<typename Type, typename Func>
  void doit(Func f) {
    Some::staticFunction<Type>(bind(f, this, _1));
  }
};
Run Code Online (Sandbox Code Playgroud)

之后你可以打电话

doit<templateType>(FuncPointer);
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你可以继承这个功能

// T must be a derived class of MyRegister<T>
template<typename T>
class MyRegister {
protected:
  template<typename Type, typename Func>
  void doit(Func f) {
    Some::staticFunction<Type>(bind(f, (T*)this, _1));
  }
};

class MyClass : MyRegister<MyClass> {
  // ...
};
Run Code Online (Sandbox Code Playgroud)

这样你就可以使用doit而不是先写它,就像使用宏一样.如果您使用该函数的各种类很有用.

编辑:请注意,由于私有继承,此处需要 C-Style强制转换(不能使用static_cast).这是一个安全的演员,如果T来自MyRegister<T>


就个人而言,我更喜欢这个宏.请注意,您的宏无法处理类型名称中的逗号

DO(std::pair<A, B>, g);
Run Code Online (Sandbox Code Playgroud)

这会尝试将3个参数传递给宏而不是2.您可以反转类型和函数的顺序并使用可变参数宏(这是一个C++ 0x特性,但在C++ 03模式下的某些编译器中可用)或者您可以使用typedef并传递别名.

  • +1:引人入胜.我不知道你可以使用C风格的强制转换静态转换为无法访问的基础. (3认同)