如何写`is_complete`模板? [英] How to write `is_complete` template?

查看:154
本文介绍了如何写`is_complete`模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回答这个问题后,我试图找到在Boost库中的is_complete 模板,我意识到在Boost.TypeTraits中没有这样的模板。为什么Boost库中没有这样的模板?它应该是什么样子?

  //!检查类型是否完整
模板< typename T>
struct is_complete
{
static const bool value =(sizeof(T)> 0);
};

...

//所以我可以这样使用它
BOOST_STATIC_ASSERT(boost :: is_complete< T> :: value);

上述代码不正确,因为应用 sizeof 为不完整类型。






那么,什么是好的解决方案? ODR规则的情况下解决,但是有一个特定的平台解决方案,适用于我。

 

code> namespace
{
template< class T,int discriminator>
struct is_complete {
static T& getT();
static char(& pass(T))[2];
static char pass(...);
static const bool value = sizeof(pass(getT()))== 2;
};
}
#define IS_COMPLETE(X)is_complete< X,__ COUNTER __> :: value

很遗憾, COUNTER 预定义宏不是标准的一部分,因此不会在每个编译器上工作。


After answering this question I was trying to find is_complete template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like?

//! Check whether type complete
template<typename T>
struct is_complete
{   
  static const bool value = ( sizeof(T) > 0 );
};

...

// so I could use it in such a way
BOOST_STATIC_ASSERT( boost::is_complete<T>::value );

The code above is not correct, because it is illegal to apply sizeof to an incomplete type. What will be a good solution? Is it possible to apply SFINAE in this case somehow?


Well, this problem couldn't be solved in general without violating the ODR rule, but there is there a platform specific solution which works for me.

解决方案

The answer given by Alexey Malistov can be used on MSVC with a minor modification:

namespace 
{
    template<class T, int discriminator>
    struct is_complete {  
      static T & getT();   
      static char (& pass(T))[2]; 
      static char pass(...);   
      static const bool value = sizeof(pass(getT()))==2;
    };
}
#define IS_COMPLETE(X) is_complete<X,__COUNTER__>::value

Unfortunately, the COUNTER predefined macro is not part of the standard, so it would not work on every compiler.

这篇关于如何写`is_complete`模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆