搜索我发现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
如何确定给定指针的类型?这段代码看起来很复杂,如果我不理解它的工作原理,我将不满意。
使用
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);
};
虽然这不是您问题的直接答案,但我发现此表达更容易理解:
decltype(std::declval<my_class>().field)