传统上,如果我想获得一个类的私有(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;
}
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;
}
最佳答案
主要问题是 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 specialization作为
template<>
const auto& myClass::get_prop<1>() const {
return age;
}
template<>
const auto& myClass::get_prop<2>() const {
return name;
}
关于c++ - 如何为类编写 "get"方法模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59487238/