c++ - 如何为类编写 "get"方法模板

标签 c++ templates

传统上,如果我想获得一个类的私有(private)属性,我只需要为它声明一个 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;
}

但是编译器报错: build message
如果我像这样添加一个指定返回类型的参数:

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

编译器报错: new build message
有人可以告诉我如何编码吗?

最佳答案

主要问题是 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>()这样调用它.

LIVE

C++17之前你可以申请template specialization作为

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

LIVE

关于c++ - 如何为类编写 "get"方法模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59487238/

相关文章:

android - 映射共享库时出错

c++ - 我是否需要在析构函数中使成员变量无效?

c++ - 谷歌oauth2.0,必需的参数丢失: grant_type

c++ - 具有非参数模板类型的类构造函数

c++ - 避免错过包含相同文件的最佳方法是什么?

c++ - 模板参数推导是否考虑了返回类型?

c++ - 获取没有显式特征的整数模板参数的有符号/无符号变体

模板化类对象的 C++ vector

c++ - 将模板与作用域在函数内的匿名类一起使用

c++ - 在接收问题上阻塞套接字超时