这是我的方式来做你想在C++ 11。它使用元组和模板。这并不简短,但如果你在头文件中包装一些代码是可以接受的。 我有完整的可编译示例:
#include <iostream>
#include <string>
using namespace std;
#include <tuple>
//Our iteratation code
//first a iteration helper structure
template<int N = 0>
struct IterateP {
template<class T>
typename std::enable_if<(N < std::tuple_size<T>::value), void>::type
iterate(T& t) {
std::get<N>(t).sharedMethod(); //there is the method name
IterateP<N+1>().iterate<T>(t);
}
template<class T>
typename std::enable_if<!(N < std::tuple_size<T>::value), void>::type
iterate(T&) {}
};
//wrapper of the helper structure for a more comfortable usage
template <typename T>
void iterate(T& t) { IterateP<>().iterate(t.members); } //look at the .members, is the name of the class tuple
//Helper notation macro.
#define MEMBER(name, i) std::tuple_element<i,decltype(members)>::type &name = std::get<i>(members)
//YOUR CLASSES
struct AnotherClass {
int value;
void sharedMethod() { cout << value << endl; }
};
struct YetAnotherClass {
string value;
void sharedMethod() { cout << value << endl; }
};
//The class with iterable members
struct Example {
std::tuple<AnotherClass, AnotherClass, YetAnotherClass> members; //members must be in a tuple
//These are helper member definition to access the tuple elements as normal members (instance.member1)
//If you don't you this you need to access the members with tuple classes
MEMBER(member1, 0); //first param is the member name and the second is it's position in the tuple.
MEMBER(member2, 1);
MEMBER(member3, 2);
};
//USAGE
int main() {
Example example;
//setting members just as a normal class
example.member1.value = 1;
example.member2.value = 2;
example.member3.value = "hola";
//magic
iterate(example);
}
我真的不认为这是一个好主意。如果你需要迭代一些东西,然后把它声明为一个可迭代的容器,或者你为什么不这样做? – leftaroundabout
检出boost序列化 –
C++没有反射。这意味着这是不可能的。 –