如何编写`is_complete`模板?

How to write `is_complete` template?(如何编写`is_complete`模板?)
本文介绍了如何编写`is_complete`模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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 );

上面的代码是不正确的,因为将 sizeof 应用于不完整的类型是非法的.什么是好的解决方案?在这种情况下是否可以以某种方式应用 SFINAE?

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?

好吧,如果不违反ODR 规则,一般无法解决这个问题,但是有一个特定于平台的解决方案对我有用.

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.

推荐答案

Alexey Malistov 给出的答案稍加修改即可用于 MSVC:

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

不幸的是,__COUNTER__ 预定义宏不是标准的一部分,因此它不适用于每个编译器.

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)