如何为类编写“获取”方法模板

停止

传统上,如果要获取类的私有属性,则必须仅为其声明一个get方法。现在,我想要一个get方法,该方法将返回其类中的任何属性,以防该类具有许多要获取的属性。我想要的是:

function get_prop(attr_index)
input: the property's index inside class declaration
output: that property's value as constant.

我尝试了这个:

#include<iostream>
#include<string>
class myClass{
private:
long age;
std::string name;
public:
myClass(long = 0, string = "");
template<typename T>
const T& get_prop(int) const;      //line 10
};
myClass::myClass(long _age, std::string _name): age(_age), name(_name){}
template<typename T>
const T& myClass::get_prop(int prop_index) const {
switch(prop_index){
case 1: return age;
case 2: return name;
}
}
int main(){
myClass ob1(10,"someone");
std::cout<<ob1.get_prop(1);        //line 22
return 0;
}

但是编译器给出了错误:如果我添加一个指定返回类型的参数,如下所示:建立讯息

class myClass{
...
template<typename T>
const T& get_prop(int, T) const;
...
};
template<typename T>
const T& myClass::get_prop(int prop_index, T) const {
switch(prop_index){
case 1: return age;           //line 16
case 2: return name;          //line 17
}
}
int main(){
myClass ob1(10,"someone");
std::cout<<ob1.get_prop(1,int());//line 22
return 0;
}

编译器给出以下错误:有人可以告诉我如何编写代码吗?新建消息

songyuanyao

主要问题是prop_index必须在编译时知道。您可以将其设为模板参数并应用constexpr if(自C ++ 17起)。

例如

template<int prop_index>
const auto& myClass::get_prop() const {
if constexpr (prop_index == 1)
    return age;
else
    return name;
}

然后称它为ob1.get_prop<1>()

生活

在C ++ 17之前,您可以将模板专业化应用

template<>
const auto& myClass::get_prop<1>() const {
    return age;
}
template<>
const auto& myClass::get_prop<2>() const {
    return name;
}

生活

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章