宏和函数中的"this"指针 [英] 'this' pointer in macro and function
问题描述
我有一些代码,该代码使用调用此代码的类的"this"指针.例如:
I have some code which use 'this' pointer of class which calls this code. For example:
Some::staticFunction<templateType>(bind(FuncPointer, this, _1));
这是我从boost调用bind函数.但这没关系.现在,我必须包装此代码.我做了一个宏:
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));
然后编译器将此代码插入到调用此宏的类中,因此"this"取自调用者.但是我不想使用宏并且更喜欢函数(内联).但是如何解决这个"过去.我可以在宏等内联函数中使用它,还是必须手动传递它?
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?
推荐答案
this
关键字可以由您调用的函数放置
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));
}
};
之后您可以致电
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> {
// ...
};
这样,您就可以只使用doit
而不是先编写它,就像使用宏一样.如果您在其中使用函数的种类很多,则很有用.
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.
注意,由于私有继承,此处C-Style强制转换是必需的(不能使用static_cast
).如果T
是从MyRegister<T>
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);
这尝试将3个参数传递给宏而不是2.您可以颠倒类型和函数的顺序,并使用可变参数宏(这是C ++ 0x功能,但在C ++的某些编译器中可用) 03模式),也可以使用typedef并传递别名.
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.
这篇关于宏和函数中的"this"指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!