我使用g ++ 4.6.3(目前是ubuntu 12.04的默认包),标志为c ++ 0x,我偶然发现:
template <typename T>
inline T getValue(AnObject&)
{
static_assert(false , "this function has to be implemented for desired type");
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
static_assertion failed "this function has to be implemented for the desired type"
Run Code Online (Sandbox Code Playgroud)
即使我还没有在任何地方调用此功能.
这是一个g ++错误吗?只有在代码中的某处调用此函数时,才应该实现此函数.
当表达式取决于类类型本身时,有没有办法在类内进行 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)