首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有什么方法可以避免警告/错误模板实例化回溯吗?

有什么方法可以避免警告/错误模板实例化回溯吗?
EN

Stack Overflow用户
提问于 2015-03-03 01:42:45
回答 1查看 1.1K关注 0票数 1

我花了一些时间在上面,完全不知道这是否可能。因此,我想我会在这里问。那么,有没有什么聪明的方法可以在显示警告/错误的时候强制不打印模板回溯到gcc/clang?

示例:

代码语言:javascript
复制
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>{};
}

提供:

代码语言:javascript
复制
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.

因此,预期的结果将是例如:

代码语言:javascript
复制
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-backtrace-limit=1 -ferror-limit=1,但我想知道是否有可能从源代码中做到这一点。

为什么我需要这样的功能?嗯,我正在通过enable-if使用概念模拟,但不幸的是,我的概念结构中有模板转换运算符,不能只返回值和静态断言或enable-if,因为信息不再可用。因此,我想也许warning + concept可以解决这个问题。假设我仍然保留这个概念,并打印一行警告和有用的东西,然后像往常一样使用enable-if禁用该功能。

EN

回答 1

Stack Overflow用户

发布于 2015-03-03 03:51:51

您可以使用别名而不是类/结构来接近:

代码语言:javascript
复制
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>{};
}

输出:

代码语言:javascript
复制
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.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28816162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档