基本上,我很好奇你是否可以使用C++ 11模板来实现它,因此模板化函数可以检测迭代器的间接级别,并根据不同的方式编译函数.例如,以下是一些无法编译的代码:
#include <vector>
#include <list>
#include <type_traits>
#include <iostream>
struct MyStruct
{
int value;
MyStruct(int value = 42) : value(value) { }
const int& getInt() const { return value; }
};
typedef std::list<MyStruct> StructList;
typedef std::vector<const MyStruct*> StructPtrVector;
template <typename ITER_TYPE>
const int& getIteratorInt(ITER_TYPE iter)
{
if (std::is_pointer<decltype(*iter)>::value)
return (*iter)->getInt(); // Won't compile -> MyStruct has no operator-> defined
return iter->getInt(); // Won't compile -> MyStruct* has the wrong level of indirection
}
template <typename LIST_TYPE>
void PrintInts(const LIST_TYPE& …Run Code Online (Sandbox Code Playgroud)