我尝试通过一些面向对象编程来练习C++,因此有了这样的类:
class Obj
{
protected:
cls1 class1;
cls2 class2;
......
clsn classn;
}
我想将这些成员设置为protected
。那么问题就变成了其他函数如何调用类数据成员来检索/修改其值。一个常见的解决方案是通过getter/setter函数。但是为每个成员编写每个getter和setter会很麻烦。所以,我能否通过模板实现一个统一的getter/setter成员函数?
class Obj
{
template<typename T> int get_stats(){
...
// maybe using is_same_v<T,cls1> to get what class of data member I attempt to access
// thus confirm the data member to access?
};
template<typename T> void add_stats();
}
这是可能的,或者有其他功能吗?
std::array
中。然后一个带有索引参数的getter和setter就可以工作了。 - johnstd::tuple<>
是不同的类,但是这可能会起作用。 - lorro