2015-03-02 69 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. 
相關問題