在回答这问题之后,我试图在Boost库中找到is_complete模板,我意识到Boost.TypeTraits中没有这样的模板。为什么在Boost库中没有这样的模板?它应该是什么样的?
//! 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规则的情况下解决的,但是有一个特定于平台的解决方案为我工作。
发布于 2009-12-24 01:14:41
Alexey Malistov给出的答案可以用在MSVC上,只需稍作修改:
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__预定义的宏不是标准的一部分,所以它不能在每个编译器上工作。
发布于 2016-05-12 16:54:53
这可能有点晚,但到目前为止,没有一个C++ 11解决方案可以同时适用于完整类型和抽象类型。
所以,你来了。
使用VS2015 (v140)、g++ >= 4.8.1、clang >= 3.4,这是可行的:
template <class T, class = void>
struct IsComplete : std::false_type
{};
template <class T>
struct IsComplete< T, decltype(void(sizeof(T))) > : std::true_type
{};使用VS2013 (V120):
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未完成?。
发布于 2009-10-26 15:03:16
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;
};https://stackoverflow.com/questions/1625105
复制相似问题