'this' pointer in macro and function

2019-07-25 16:52发布

I have some code which use 'this' pointer of class which calls this code. For example:

Some::staticFunction<templateType>(bind(FuncPointer, this, _1));

Here is I'm calling bind function from boost. But it doesn't matter. Now I have to wrap this code. I made a macro:

#define DO(Type, Func) Some::staticFunction<Type>(bind(FuncPointer, this, _1));

And compiler insert this code into class which calls this macro, so 'this' takes from caller. But I don't want to use macro and prefer function (inline). But how to resolve 'this' passing. Could I use it in inline function like in macro or I have to pass it manually?

2条回答
够拽才男人
2楼-- · 2019-07-25 17:05

The this keyword can be put by the function you call

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

After which you can call

doit<templateType>(FuncPointer);

If you like you can inherit the function

// 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> {
  // ...
};

That way you can just use doit and not first write it, just like with the macro. Useful if you have a wide range of classes that you use the function in.

Edit: Notice that the C-Style cast is required here (can't use static_cast), because of the private inheritance. It's a safe cast if T is derived from MyRegister<T>


Personally i would prefer this over the macro. Notice that your macro can't cope with commas in the type-name

DO(std::pair<A, B>, g);

This tries to pass 3 arguments to the macro instead of 2. You could reverse the order of the type and the function and use variadic macros (which are a C++0x feature, but available in some compiler in C++03 mode) or you could use a typedef and pass the alias name.

查看更多
一夜七次
3楼-- · 2019-07-25 17:05

An inline function is a regular function and must be compilable by itself. The inline keyword is simply a suggestion to the compiler to put the actual function body where the function is called, for optimization reasons. In the specific an inline function cannot access names that are visible only at the place of calling (in your case "this"), so you must pass them as parameters.

On the other hand a macro is just a text expansion happening at preprocessing time, so the macro body is not required to have a meaning by itself and everything is ok as long as the final expansion you end up with is legal C++ code.

For example you can have a macro "opening" a for loop and another macro "closing" it (something that clearly an inline function cannot do).

查看更多
登录 后发表回答