定义非静态成员时获取C++中的"this"类型



我正在尝试做一些花哨的模板内容,但我偶然发现了一个问题:我想在其定义中获取类的类型,同时定义一个非静态成员。这可能吗?(在任何C++版本中。


采用以下代码:

template<typename T>
struct inner {
T* this_;
/* fancy stuff... */
};
struct foo {
inner<foo> bar{this};
};

foo具有使用指针foo* this初始化的非静态成员bar。这段代码用 clang 和 gcc 编译。

但我实际上希望inner的定义出现在宏中,这意味着我没有字符串foo在行inner<foo> bar{this}中使用。尝试使用:

inner bar{this};

在 C++17 中,允许类模板的模板参数推导,产生错误

错误:使用类模板"inner"需要模板参数;在非静态结构成员inner bar{this};中不允许参数推导

我明白。正在尝试:

inner<decltype(*this)> bar{this};

产生类似的外观错误:

错误:在非静态成员函数inner<decltype(*this)> bar{this};之外无效使用"this"


作为一种解决方法,我一直在使用以下奇怪的重复出现的模板模式:

template<typename T>
struct SelfAwareType {
using myOwnType = T;
}
struct foo : SelfAwareType<foo> {
inner<myOwnType> bar{this};
};

如果你可以限制所有 foo 需要 typedef 'this_type',那么你的宏可能不需要指定 foo。

template<typename T>
struct inner {
T* this_;
/* fancy stuff... */
};
struct foo {
typedef foo this_type ;
inner<this_type> bar{this};
};

这与您的"解决方法"基本相同,而无需使用 CRTP 并引入另一种类型。

最新更新