Gio*_*hal 6 c++ templates static-assert type-traits
当表达式取决于类类型本身时,有没有办法在类内进行 static_assert ?也许延迟评估直到类型完成或模板实例化之后?
示例代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是使用辅助类和类型别名进行间接寻址的解决方案。我相信这没有任何缺点。
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;
Run Code Online (Sandbox Code Playgroud)
编辑:或者可以将 TestHelper 移至 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;
Run Code Online (Sandbox Code Playgroud)