for*_*818 3 c++ templates static-assert c++03
我试图使用pre-C++ 11静态断言.我找到了这个和这个问题,但不知怎的,我不能让它运行:
#define STATIC_ASSERT(x) \
do { \
const static char dummy[(x)?1:-1] = {0};\
} while(0)
struct bar {
int value;
template<typename T> void setValue(T x);
};
template<typename T> void bar::setValue(T x) { STATIC_ASSERT(1==0); }
template<> void bar::setValue(int x) { value = x;}
int main(){
bar b;
int c = 1;
b.setValue(c);
}
Run Code Online (Sandbox Code Playgroud)
编译此(gcc)会导致
错误:数组'dummy'的大小为负数
我希望只有当我setValue用除了以外的任何东西打电话时才会出现这个错误int.我也尝试了其他提出的解决方案,但结果大致相同:即使我没有用除了以外的任何东西实例化模板,也会出现错误int.我究竟做错了什么?
如果模板对于每个实例化都无效,则程序格式错误,无需诊断.因此,GCC在此处给出错误是完全有效的,因为setValue无论模板参数是什么,主要模板都是无效的.
解决此问题的方法是使STATIC_ASSERT表达式依赖于模板参数.一个选项是创建一个dependent_false模板类,如下所示:
template <typename T> struct dependent_false
{ const static bool value = false; };
template<typename T> void bar::setValue(T x)
{ STATIC_ASSERT(dependent_false<T>::value); }
Run Code Online (Sandbox Code Playgroud)