根据 g++ 手册页及其网站https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html,以下代码在使用 -O3 -Wstrict-overflow=5 编译时应产生警告:
#include <iostream>
#include <limits>
int
main() {
int x{std::numeric_limits<int>::max()};
if(x+1 > x) std::cout << "Hello";
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/57ccc33f3
它甚至输出“Hello”,表明它优化了 check(x+1 > x) 。但是我没有收到任何警告。我误解了这个警告的意思还是这是一个 gcc 错误?我在他们的错误数据库中找不到任何东西。
我们可以为这样的多维数组添加别名:
template<typename T, size_t size1, size_t size2>
using myArray = std::array<std::array<T, size2>, size1>;
Run Code Online (Sandbox Code Playgroud)
但这只允许我们预定义数量的维度.有没有办法将其转换为可变参数模板,以便我们可以编写以下任何一个:
myArray<int, 2, 2, 2> arr3d;
myArray<int, 2, 2, 2, 2> arr4d;
Run Code Online (Sandbox Code Playgroud)
我尝试过一些东西,但对它们中的任何一个都不满意.
这个:
template<typename T, size_t size>
using myArray<T, size> = std::array<T, size>;
template<typename T, size_t size, size_t... more>
using myArray = std::array<myArray<T, more...>, size>;
Run Code Online (Sandbox Code Playgroud)
甚至不编译,因为别名模板显然不允许模板特化.
这是我目前最好的解决方案,但删除了我想保留的std :: array的所有构造函数:
template<typename T, size_t size, size_t... more>
struct myArray : public std::array<myArray<T, more...>, size> {};
template<typename T, size_t size>
struct myArray<T, size> : public std::array<T, size>{};
Run Code Online (Sandbox Code Playgroud)
有了这个解决方案,我总是要在每个数组访问前写".internal":
template<typename …Run Code Online (Sandbox Code Playgroud) 我尝试实现指向非指针的唯一指针,如下所述: One-liner for RAII on non pointer? 和https://dzone.com/articles/c11-smart-pointers-are-not。但我总是得到一个编译器错误:/usr/include/c++/5/bits/unique_ptr.h:235:12: error: invalid operands of types 'unsigned int' and 'std::nullptr_t' to binary 'operator!= '
这是我的代码:
struct ShaderDeleter
{
typedef GLuint pointer; // Note the added typedef
void operator()(GLuint shader) {
glDeleteShader(shader);
}
};
int main() {
std::unique_ptr<GLuint, ShaderDeleter> smart_shader{glCreateShader(GL_VERTEX_SHADER)};
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
平台:Ubuntu 16.04
编译器:g++