c++ - 有没有办法避免警告/错误模板实例化回溯?

标签 c++ c++11 gcc clang

花了一些时间,完全不知道它是否可行。因此我想我会在这里问。那么,有什么聪明的方法可以在 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-backtrace-limit=1 -ferror-limit=1,但我想知道是否有可能从源代码中做到这一点。

为什么我需要这样的功能?好吧,我正在通过 enable-if 使用概念模拟,但不幸的是,我的概念构造中有模板转换运算符,不能只返回值和静态断言或启用-if,因为信息不再可用。因此我认为警告+概念可能会做这件事。假设我仍然有这个概念,并打印一行警告和有用的东西,然后像往常一样使用 enable-if 禁用该功能。

最佳答案

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

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.

关于c++ - 有没有办法避免警告/错误模板实例化回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816162/

相关文章:

C++ 在 eof() 循环中使用迭代器进行分词

c++ - 将 weak_ptr 与 unique_ptr 配对是个好主意吗?

c++ - 是否有 posix_memalign 的 c++ 对应项?

c++ - 跨 C++0x 编译器的 lambda 特征不一致

c++ - 如何解决 gcc 4.7 和 4.9 之间 std::vector 的不同行为?

Linux/海湾合作委员会 : ldd functionality from inside a C/C++ program

c++ - 哪种访问 C++ 枚举数的方式更好?

c++11 - C++98 和 C++11 之间的哪些变化显示了行为差异?

c++ - 将 vector 传递给某些需要某种大小的数组引用的遗留 API 的任何方法

security - 如何使用 GCC 和 Clang(或一般的 LLVM)减轻 Spectre