静态断言模板类型名称T不完整? [英] static assert that template typename T is NOT complete?
问题描述
有一种方法static_assert,类型T是不在标题中的那一点完成?这个想法是有一个编译错误,如果有人在路上添加#includes在他们不应该是的地方。
Is there a way to static_assert that a type T is Not complete at that point in a header? The idea is to have a compile error if someone adds #includes down the road in places they should not be.
使用该链接的答案,
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!");
不幸的是,这会导致无效使用收入类型错误。有没有办法断言否定?
unfortunately this gives "invalid use of incomlete type" error, d'oh. Is there a way to assert on the negation?
推荐答案
这里是一个使用表达式SFINAE的函数,基于 chris 提案,可以检查类型是否完整。
我的采用需要没有包括,错误输出当所需的参数缺失(隐藏参数是不可能的),并适合C ++ 11以上。
Here is a function using expression SFINAE based on chris proposal which allows checking whether a type is complete yet.
My adoption needs no includes, errors-out when the required argument is missing (hiding the argument was not possible) and is suitable for C++11 onward.
template<typename T>
constexpr auto is_complete(int=0) -> decltype(!sizeof(T)) {
return true;
}
template<typename T>
constexpr bool is_complete(...) {return false;}
套件:
struct S;
bool xyz() {return is_complete<S>(0);}
struct S{};
#include <iostream>
int main() {
std::cout << is_complete<int>(0) << '\n';
std::cout << xyz() << '\n';
std::cout << is_complete<S>(0);
}
输出:
1
0
1
这篇关于静态断言模板类型名称T不完整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!