如何确定C ++ 03中的类型是否可解除引用?

时间:2013-12-30 05:58:11

标签: c++ dereference

C ++ 03 中,如何确定类型T是否可解除引用?
我的意思是,我如何静态确定*t是否为tT的有效表达式?

我的尝试:

template<bool B, class T = void> struct enable_if { };
template<class T> struct enable_if<true, T> { typedef T type; };

unsigned char (&helper(void const *))[2];
template<class T>
typename enable_if<
    !!sizeof(**static_cast<T *>(NULL)),
    unsigned char
>::type helper(T *);

template<class T>
struct is_dereferenceable
{ static bool const value = sizeof(helper(static_cast<T *>(NULL))) == 1; };

struct Test
{
    int *operator *();
    void operator *() const;
private:
    Test(Test const &);
};

int main()
{
    std::cout << is_dereferenceable<int *>::value;       // should be true
    std::cout << is_dereferenceable<void *>::value;      // should be false
    std::cout << is_dereferenceable<Test>::value;        // should be true
    std::cout << is_dereferenceable<Test const>::value;  // should be false
}

它适用于GCC(打印1010)但在VC ++(1110)和Clang(1111)上崩溃和灼伤。

2 个答案:

答案 0 :(得分:3)

#include <boost\type_traits\remove_cv.hpp>
#include <boost\type_traits\is_same.hpp>
#include <boost\type_traits\remove_pointer.hpp>
#include <boost\type_traits\is_arithmetic.hpp>
#include <boost\utility\enable_if.hpp>

namespace detail
{
    struct tag 
    { 
        template < typename _T > 
        tag(const _T &); 
    };

    // This operator will be used if there is no 'real' operator
    tag operator*(const tag &);

    // This is need in case of operator * return type is void
    tag operator,(tag, int);  

    unsigned char (&helper(tag))[2];

    template < typename _T >
    unsigned char helper(const _T &);

    template < typename _T, typename _Enable = void >
    struct traits
    {
        static const bool value = (sizeof(helper(((**static_cast <_T*>(NULL)), 0))) == 1);
    };

    // specialization for void pointers
    template < typename _T >
    struct traits < _T,
        typename boost::enable_if < typename boost::is_same < typename boost::remove_cv < typename boost::remove_pointer < _T > ::type > ::type, void > > ::type >
    {
        static const bool value = false;
    };

    // specialization for arithmetic types
    template < typename _T >
    struct traits < _T,
        typename boost::enable_if < typename boost::is_arithmetic < typename boost::remove_cv < _T > ::type > > ::type >
    {
        static const bool value = false;
    };
}

template < typename _T > 
struct is_dereferenceable :
    public detail::traits < _T >
{ };

我已在msvs 2008中测试过它

答案 1 :(得分:1)

这是铿锵的错误。有人应该提交一份报告。

Clang实现了对void指针进行指针运算的旧gcc扩展。这包括能够取消引用void指针,并取sizeof(void)。 Clang是这样做的,因为人们曾经抱怨旧代码可以与gcc编译而不是clang。因此clang维护者继续实施此扩展。这里的问题很多:

  1. 使用gcc,扩展程序始终使用C编译器进行静默处理,但是使用C ++编译器生成警告。使用clang时,如果使用扩展名,则默认情况下C和C ++编译器都是静默的。
  2. 使用g ++时,sizeof(void)在模板中使用时会产生替换失败,尽管只是一个警告。使用clang ++,它没有。
  3. 您可以使用-Wpointer-arith -Werror禁用clang ++中的扩展名,但这会导致sizeof(void)成为编译错误而不是替换失败。
  4. 我不能保证VC ++。