首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何编写`is_complete`模板?

如何编写`is_complete`模板?
EN

Stack Overflow用户
提问于 2009-10-26 14:21:54
回答 9查看 5K关注 0票数 30

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

代码语言:javascript
复制
//! 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?

嗯,这个问题一般是不能在不违反ODR规则的情况下解决的,但是有一个特定于平台的解决方案为我工作。

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2009-12-24 01:14:41

Alexey Malistov给出的答案可以用在MSVC上,只需稍作修改:

代码语言:javascript
复制
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__预定义的宏不是标准的一部分,所以它不能在每个编译器上工作。

票数 19
EN

Stack Overflow用户

发布于 2016-05-12 16:54:53

这可能有点晚,但到目前为止,没有一个C++ 11解决方案可以同时适用于完整类型和抽象类型。

所以,你来了。

使用VS2015 (v140)、g++ >= 4.8.1、clang >= 3.4,这是可行的:

代码语言:javascript
复制
template <class T, class = void>
struct IsComplete : std::false_type
{};

template <class T>
struct IsComplete< T, decltype(void(sizeof(T))) > : std::true_type
{};

感谢Bat-Ulzii:https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/

使用VS2013 (V120):

代码语言:javascript
复制
namespace Details
{

    template <class T>
    struct IsComplete
    {
        typedef char no;
        struct yes { char dummy[2]; };

        template <class U, class = decltype(sizeof(std::declval< U >())) >
        static yes check(U*);

        template <class U>
        static no check(...);

        static const bool value = sizeof(check< T >(nullptr)) == sizeof(yes);
    };

} // namespace Details


template <class T>
struct IsComplete : std::integral_constant< bool, Details::IsComplete< T >::value >
{};

这一个灵感来自于互联网和静态断言模板typename T未完成?

票数 15
EN

Stack Overflow用户

发布于 2009-10-26 15:03:16

代码语言:javascript
复制
template<class T>
struct is_complete {
    static T & getT();
    static char (& pass(T))[2];
    static char pass(...);

    static const bool value = sizeof(pass(getT()))==2;
};
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1625105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档