除非没有其他选择,否则不要使用宏,更喜欢模板。它们是类型安全的。
例如,您可以创建一个编译时评估函数 (constexpr),它合并两个列表(数组)并返回一个数组。
#include <array>
// type_t is the type held by the array (an int in this example)
// N = size of first array
// M = size of second array
// const type_t(&arr)[N] is the syntax for passing an array by const reference
template<typename type_t, std::size_t N, std::size_t M>
constexpr auto merge(const type_t(&arr1)[N], const type_t(&arr2)[M])
{
std::array<type_t, N + M> arr{}; // this initialization is needed in constexpr
std::size_t index{ 0 };
for (const auto& value : arr1) arr[index++] = value;
for (const auto& value : arr2) arr[index++] = value;
return arr;
}
int main()
{
constexpr auto arr = merge({ 1,2,3 }, { 4,5,6 });
constexpr auto strings = merge( {"abc", "def" }, {"ijk", "lmn"} );
// static_assert is like assert, but evaluated at compile time.
static_assert(arr.size() == 6);
static_assert(arr[4] == 5);
return 0;
}