【发布时间】:2014-11-05 21:57:30
【问题描述】:
有没有办法 static_assert 类型 T Not 在标头中的那个点是完整的?这个想法是如果有人在不应该的地方添加#includes,就会产生编译错误。
相关:How to write `is_complete` template?
使用该链接的答案,
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
class GType;
static_assert(!IS_COMPLETE(GType),"no cheating!");
不幸的是,这给出了“invalid use of incomlete type”错误,哦。有没有办法断言否定?
【问题讨论】:
-
既然你有C++11,你可以使用expression SFINAE。
-
@chris:你为什么要在那里介绍
declval? coliru.stacked-crooked.com/a/d2987f9901270a48 -
@Deduplicator,将
S更改为struct S {S(int){}};,您将获得0,只需使用S{}而不是std::declval<S>()。std::declval为您提供右值引用,因此您无需使用可能存在或不存在的构造函数。但是,是的,一开始这一切都是完全没有必要的,因为我很笨,sizeof适用于类型。 -
基于此:clang++ -std=c++1y -stdlib=libc++ -Wall -Wextra -pedantic-errors -O3 -pthread main.cpp /usr/lib/x86_64-linux-gnu/ libstdc++.so.6 && ./a.out #clang++ -E -P main.cpp #g++-4.9 -std=c++1y -Wall -Wextra -pedantic-errors -O3 -pthread main.cpp && ./a .out #clang -xc -std=c11 -Wall -Wextra -pedantic -O3 main.cpp && ./a.out 1 0 从发布的链接来看,即使使用 GCC 4.7x,我似乎也不走运,更不用说VS2012?好的,我将在“将来使用”下提交此文件!
标签: c++ templates static-assert incomplete-type