2015-03-02 71 views
1

花了一些时间,并完全不知道是否有可能。因此,我想我会在这里问。那么,在gcc/clang上显示警告/错误时,是否有强制不打印模板回溯的巧妙方法?有没有办法避免警告/错误模板实例化回溯?

实施例:

template<int I = 0, typename = void> 
struct warn { 
    unsigned : I; 
}; 
struct hello_world {}; 

template<int I> 
class a : warn<I, hello_world> {}; 

template<int I> 
class b : a<I>{}; 

template<int I> 
class c : b<I> {}; 

template<int I> 
class d : c<I> {}; 

int main() { 
    d<80>{}; 
} 

给出:

test.cpp:3:5: warning: size of anonymous bit-field (80 bits) exceeds size of its type; value will be truncated to 32 bits 
    unsigned : I; 
    ^
test.cpp:8:11: note: in instantiation of template class 'warn<80, hello_world>' requested here 
class a : warn<I, hello_world> {}; 
     ^
test.cpp:11:11: note: in instantiation of template class 'a<80>' requested here 
class b : a<I>{}; 
     ^
test.cpp:14:11: note: in instantiation of template class 'b<80>' requested here 
class c : b<I> {}; 
     ^
test.cpp:17:11: note: in instantiation of template class 'c<80>' requested here 
class d : c<I> {}; 
     ^
test.cpp:20:2: note: in instantiation of template class 'd<80>' requested here 
     d<80>{}; 
     ^
1 warning generated. 

所以,预期的结果将是例如:

test.cpp:3:5: warning: size of anonymous bit-field (80 bits) exceeds size of its type; value will be truncated to 32 bits 
    unsigned : I; 
    ^
test.cpp:8:11: note: in instantiation of template class 'warn<80, hello_world>' requested here 
class a : warn<I, hello_world> {}; 

有-ftemplate-回溯极限= 1 - ferror-limit = 1,但我想知道是否有可能从源代码中做到这一点。

为什么我需要这样的功能?那么,我通过enable-if使用概念模拟,但不幸的是,我的概念构造中有模板转换操作符,不能只返回值和静态断言或启用 - 如果它,因为信息不再可用。所以我认为也许警告+概念会做到这一点。比方说,我仍然会有这个概念,并用有用的东西打印一行警告,之后用enable-if像往常一样禁用该函数。

回答

2

你可以亲近使用别名来代替类/结构:

template<int I = 0, typename = void> 
struct warn { 
    unsigned : I; 
}; 
struct hello_world {}; 

template<int I> 
using a = warn<I, hello_world>; 

template<int I> 
using b = a<I>; 

template<int I> 
using c = b<I>; 

template<int I> 
using d = c<I>; 

int main() { 
    (void)d<80>{}; 
} 

输出:

test.cpp:3:5: warning: size of anonymous bit-field (80 bits) exceeds size of its type; value will be truncated to 32 bits 
    unsigned : I; 
    ^
test.cpp:20:9: note: in instantiation of template class 'warn<80, hello_world>' requested here 
    (void)d<80>{}; 
     ^
1 warning generated. 
相关问题