c++ - 返回对特定大小数组的引用,而不在返回类型中明确说明大小

标签 c++ c++11 c++14 return-type

我有以下功能:

... getX()
{
    static int x[] = {1, 2, 3};
    return x;
}

我希望它的返回类型为 int(&)[3] 但不想明确指定大小 (3)。

我该怎么做?

(请不要问为什么我想要那个。)

UPD

好吧,好的,我需要将结果传递给以 int(&x)[N] 作为参数的模板函数(并且我不想将大小显式传递给该模板函数),所以我看不出返回一对的解决方案如何工作......

最佳答案

在 C++14 中:

auto& getX()
{
    static int x[] = {1, 2, 3};
    return x;
}

另外,考虑使用 std::array而不是 C 样式的数组。


我目前想不出任何符合标准的 C++11 解决方案。这是一个使用复合字面量的例子,假设您的目标是不重复元素并推断出对数组的引用:

#include <type_traits>

#define ITEMS 1, 2, 3
auto getX() -> decltype((int[]){ITEMS})
{
    static int x[] = {ITEMS};
    return x;
}
#undef ITEMS

int main()
{
    static_assert(std::is_same<decltype(getX()), int(&)[3]>{});
}

关于c++ - 返回对特定大小数组的引用,而不在返回类型中明确说明大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46222699/

相关文章:

c++ - 完美转发 C++ 重载和模板化仿函数及其参数

c++ - std::move(key) 在迭代 unordered_map<string, string> 时?

c++ - 具有更多模板参数的部分特化

c++ - std::discrete_distribution 指定范围的随机数

c++ - 插入二叉树

c++ - 使用谷歌地图时 QWebView : Extremely laggy when dragging the map around,

c++ - 如何反转整数参数包?

c++ - 如何调用存储在char数组中的机器码?

c++ - auto&& 从 C++ lambda 返回类型

SFINAE 用于表达式和 decltype(auto)