解决静态断言中的不完整类型 [英] Work around incomplete type in static assert
本文介绍了解决静态断言中的不完整类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当表达式依赖于类类型本身时,有没有办法在类内部进行 static_assert ?也许延迟评估直到类型完成或模板实例化之后?
Is there a way to static_assert inside a class when the expression depends on the class type itself? Maybe delay the evaluation until the type is complete or after template instantiation?
示例代码:
#include <type_traits>
template<typename T>
struct Test {
T x = 0; // make non-trivial
static_assert(std::is_trivial<Test<T>>::value, "");
};
int main() {
// would like static assert failure, instead get 'incomplete type' error
Test<int> test1;
Test<float> test2;
return 0;
}
推荐答案
这是一个使用辅助类和间接类型别名的解决方案.我相信这没有缺点.
Here's a solution using a helper class and a type alias for indirection. I believe this has no drawbacks.
template<typename T>
struct TestImpl {
T x = 0; // make non-trivial
};
template<typename T>
struct TestHelper {
using type = TestImpl<T>;
static_assert(std::is_trivial<type>::value, "");
};
template<typename T>
using Test = typename TestHelper<T>::type;
或者可以将 TestHelper 移到 TestImpl 中:
edit: Alternatively TestHelper can be moved into TestImpl:
template<typename T>
struct TestImpl {
T x = 0; // make non-trivial
struct Helper {
using type = TestImpl;
static_assert(std::is_trivial<type>::value, "");
};
};
template<typename T>
using Test = typename TestImpl<T>::Helper::type;
这篇关于解决静态断言中的不完整类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文