【发布时间】:2020-03-24 13:51:16
【问题描述】:
搜索我发现this answer 的站点,用于获取类中成员的类型。 基于此,我制作了以下成功编译的示例。
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class sig_class_t{
public:
int field;
};
class usig_class_t{
public:
unsigned int field;
};
template <class T, class M> M get_member_type(M T:: *);
template<typename my_class = sig_class_t, typename my_type = decltype(get_member_type(&my_class::field))>
class Tricky{
my_type it;
public:
my_type get_it();
void set_it(my_type value);
};
template<typename my_class, typename my_type>
my_type Tricky<my_class,my_type>::get_it(){
return it;
}
template<typename my_class, typename my_type>
void Tricky<my_class,my_type>::set_it(my_type value){
it = value;
}
int main(int argc, char *argv[])
{
return 0;
}
get_member_type 如何判断给定指针的类型?
这段代码看起来很复杂,如果我不明白它是如何工作的,我会感到不舒服。
【问题讨论】:
-
例如,另一种可能是
decltype(std::declval<my_class>().field)。