使用模板中第一种类型的类成员的类型

问题描述 投票:1回答:2

搜索我发现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如何确定给定指针的类型?这段代码看起来很复杂,如果我不理解它的工作原理,我将不满意。

c++ templates decltype
2个回答
2
投票

使用

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);
};

1
投票

虽然这不是您问题的直接答案,但我发现此表达更容易理解:

decltype(std::declval<my_class>().field)

© www.soinside.com 2019 - 2024. All rights reserved.