C ++-是否有使用不变语法获取当前类类型的方法? [英] C++ - Are there ways to get current class type with invariant syntax?

查看:61
本文介绍了C ++-是否有使用不变语法获取当前类类型的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个宏,当在一个类中扩展该宏时,将使用该类类型(具体来说,作为模板参数).在类方法中,我可以使用以下方法:

I want to write a macro which, when expanded within a class, uses that class type (specifically, as template argument). Within class method, I can use this:

#define METHOD_MACRO int sample_method(void)const {\
    return template_struct<this_type<decltype(this)>::type>::index;}

(this_type是我的结构,在这里等效于 remove_pointer< remove_const< T>> ))

(this_type is my struct, here it's equivalent to remove_pointer<remove_const<T>>)

但是当我需要方法之外的类类型时(对于类成员指针的typedef), this 关键字不可用;我尝试使用 auto 来推断类型,但这里没有运气.如果有帮助,可以从我的课程中继承有问题的课程.我想避免使用我的宏的任何人都必须编写强制性的 typdedef .

But when I need class type outside of method (for typedef for class member pointer), this keyword isn't available; I've tried to use auto for some trick with deducing type, but no luck here. Classes in question are inherited from my class, if this can be of any help. I would like to avoid anyone using my macro having to write obligatory typdedef.

有什么想法吗?

推荐答案

您可以使用以下技巧:

#define SELF \
    static auto helper() -> std::remove_reference<decltype(*this)>::type; \
    typedef decltype(helper()) self

struct A {
    SELF;
};

我使用 auto 返回类型声明了一个辅助函数,这使我可以将 decltype(* this)用作返回类型,而不知道类名是什么.然后,我可以使用 decltype(helper())在代码中使用类类型.请注意,该功能必须为 static ,否则不能在 decltype 中使用它.同样,该函数只是声明而不是定义.这应该不成问题,因为无论如何您都不会称呼它.(您可以在其中添加一个空的主体,但会发出警告,该函数没有 return .仍然可以将返回类型更改为 decltype(this)并返回 nullptr .)

I declare a helper function using the auto return type, which allows me to use decltype(*this) as a return type, not knowing what is the class name. Then I can use decltype(helper()) to use the class type in the code. Note that the function has to be static, otherwise you can not use it in decltype. Also the function is just declared, not defined; this should not be a problem as you are not going to call it anyway. (You can add an empty body to it, but it will raise a warning that a function has no return. Still you may change the return type to be decltype(this) and return nullptr.)

然后可以使用 self typedef进行进一步的声明,或者仅更改宏以使typedef不是类本身,而是所需的类型.调整它以适合您的特定需求.

You may then use the self typedef for further declarations, or just alter the macros to typedef not the class itself, but what you need to. Adjust it to suit your particular need.

UPD :这似乎是GCC的非标准行为.例如,即使在尾随返回类型中,ICC也不允许在 static 函数中使用 this .

UPD: This seems to be a non-standard behavior of GCC. For example, ICC does not allow this in static functions even in trailing return type.

这篇关于C ++-是否有使用不变语法获取当前类类型的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆