【发布时间】:2021-04-08 10:48:23
【问题描述】:
有没有办法在顶级的struct声明中通用获取struct的类型,没有指的是struct的实际名称自己?
例如:
#include <type_traits>
struct example {
using attempt1 = example; // <- obvious, but not what I want
using attempt2 = decltype(*this); // <- error
using attempt3 = std::remove_pointer<decltype(this)>::type; // <- error
};
或者:
#include <type_traits>
struct { // anonymous
//using attempt1 = ...;
using attempt2 = decltype(*this);
using attempt3 = std::remove_pointer<decltype(this)>::type;
} x;
这些程序当然无法在 GCC 9.x 和 10.x 上的 C++17 和 C++2a 模式下编译(“在顶层无效使用 'this'”),但我想执行attempt2 或attempt3 之类的操作,我可以在不提及其名称的情况下获取struct 的类型(在第一种情况下为“example”)。
这可能吗?
我浏览了<type_traits>,但什么都没有出现,我想不出还有哪里可以看。
【问题讨论】:
-
我能找到的最接近的东西是这个,看看它是否对你有帮助 stackoverflow.com/a/26274842/791430 或这个 stackoverflow.com/a/33232825/791430 谷歌这个词
class而不是struct以获得更好的结果 -
你能做一个
template <class T> class SelfTypeHolder { using SelfType = T; };并像class SomeClass: public SelfTypeHolder<SomeClass>{};一样使用它,就像奇怪的重复模板一样吗? -
不幸的是,似乎可用的解决方案仅在用于结构的非静态函数时才有效。 stackoverflow.com/questions/1666802/is-there-a-class-macro-in-c
-
谢谢大家,等我回到家,我会回顾一下上面的 cmets 中的链接,然后这个评论会自毁。