我正在阅读 http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/ 并遇到此代码以检查类型是否为指针:

template<class T> struct
isPtr {
 static const bool value = false;
};

template<class U> struct
isPtr<U*> {
 static const bool value = true;
};

template<class U> struct
isPtr<U * const> {
 static const bool value = true;
};

我如何专门使用通用模板来处理指向 const 类型的 const 指针的大小写?
如果我这样做:
std::cout << isPtr <int const * const>::value << '\n';

当我期待虚假时,我得到了真实。
有人可以解释一下吗?

编辑:使用 VC++ 2010 编译器(表达 :-)

最佳答案

结果是正确的;当您调用 isPtr <int const * const> 时会调用您的第三个特化;您正在设置为 true

在这种情况下,您可以选择 enum 而不是 bool,因为您有 3 个状态:

enum TYPE
{
  NOT_POINTER,
  IS_POINTER,
  IS_CONST_POINTER
};

template<class T> struct
isPtr {
 static const TYPE value = NOT_POINTER;
};

template<class U> struct
isPtr<U*> {
 static const TYPE value = IS_POINTER;
};

template<class U> struct
isPtr<U * const> {
 static const TYPE value = IS_CONST_POINTER;
};

这是 the demo

关于c++ - 指向 const 类型的 const 指针的模板特化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6741691/

10-11 22:57
查看更多