关于模板:定义非静态成员时,在C ++中获取“ this”的类型

Getting type of “this” in C++ when defining non-static member

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

采取以下代码:

1
2
3
4
5
6
7
8
9
template<typename T>
struct inner {
    T* this_;
    /* fancy stuff... */
};

struct foo {
    inner<foo> bar{this};
};

foo具有一个用指针foo* this初始化的非静态成员bar。 此代码使用clang和gcc进行编译。

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

inner bar{this};

在C ++ 17中,它允许为类模板推导模板参数,从而产生错误

error: use of class template 'inner' requires template arguments; argument deduction not allowed in non-static struct member inner bar{this};

我了解。 试:

inner bar{this};

产生类似的外观错误:

error: invalid use of 'this' outside of a non-static member function inner bar{this};

解决方法是,我一直在使用以下奇怪的重复模板模式:

1
2
3
4
5
6
7
8
template<typename T>
struct SelfAwareType {
    using myOwnType = T;
}

struct foo : SelfAwareType<foo> {
    inner<myOwnType> bar{this};
};


如果您可以约束所有foo以要求使用typedef'this_type',则您的宏可能无需指定foo。

1
2
3
4
5
6
7
8
9
10
template<typename T>
struct inner {
    T* this_;
    /* fancy stuff... */
};

struct foo {
    typedef foo this_type ;
    inner<this_type> bar{this};
};

这与您的"解决方法"基本相同,而不必使用crtp并引入其他类型。