小编Com*_*bot的帖子

是一个模板化的函数,它支持C++ 11中不同级别的间接?

基本上,我很好奇你是否可以使用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)

c++ templates generic-programming c-preprocessor c++11

3
推荐指数
1
解决办法
287
查看次数