这个宏用于写出100%安全的任何数组内容吗?C++ 11

xin*_*aiz -1 c++ arrays macros for-loop c++11

我知道C++没有很好的宏功能,但我发现了这一点.

#define show(array)              \
    for (auto& x : (array))      \
    std::cout << x << std::endl; \
Run Code Online (Sandbox Code Playgroud)

我们不能有内联函数替代这个宏,因为数组被发送作为指针,所以这是不可能的.有了这个,即使我们尝试应用一些不雅的东西,它也只会导致编译时错误(如果对象不可迭代),而且很明显:

'begin' was not declared in this scope: show(5);
Run Code Online (Sandbox Code Playgroud)

然后我的问题 - 这绝对安全吗?它会导致造成"糟糕的情况"吗?

vso*_*tco 10

可以使用100%C++模板函数,其中数组不会衰减为指针,方法是通过引用传递数组并推断其大小和类型:

template<typename T, size_t N>
void print_arr(const T(&arr)[N])
{
    for(auto&& elem: arr)
        std::cout << elem;
}
Run Code Online (Sandbox Code Playgroud)

Live on Coliru

宏很少是安全的,所以更喜欢使用(如果可以)正确的功能,这是类型检查等.