从初始化列表中返回一个值

Returning a value from an initializer list

我有一个 switch 语句,其中 returns 一个基于提供的索引的值。

switch (index) {
  case 0: 
    return arr_1[index];
  case 1: 
    return arr_2[index];
  // and so on
}

而不是使用 "arr_1" 或 "arr_2",我想写这样的东西:

switch (index) {
  case 0: 
    return {1, 2, 3}[index];
  case 1: 
    return {10, 45, 199}[index];
  // and so on
}

这样的事情可能吗?

编辑:

我尝试过的事情:

您实际上可以为此使用 std::array。像下面这样的东西应该可以工作:

int idx = 0;
std::cout << std::array<int, 3>{1, 2, 3}[idx] << "\n";

遗憾的是,这非常冗长。这是一个工作示例:

#include <iostream>
#include <array>

int testFunction()
{
    int index = 0;
    switch (index)
    {
    case 0:
        return std::array<int, 3>{1, 2, 3}[index];
    case 1:
        return std::array<int, 3>{10, 45, 199}[index];
    }
}

int main()
{
    std::cout << testFunction() << "\n";
}

如果 std::initializer_list 实施了索引运算符,那么您的代码段可能有效。但是,如果您真的想使用初始化列表,则可以使用以下内容:

#include <iostream>
#include <initializer_list>

using inl = std::initializer_list<int>;

int testFunction()
{
    int index = 0;
    switch (index)
    {
    case 0:
        return (inl{1, 2, 3}.begin())[index];
    case 1:
        return (inl{10, 45, 199}.begin())[index];
    }
}

我不推荐这个,因为与第一个实现相比它不清楚。

您不能 return / 访问 std::initializer_list by index as the std::initializer_list does not provide a subscript operator nor a member function allowing you to access element by index. Use the container that does implement a subscript operator such as std::array, std::vector 或类似的值。

一点模板魔法,没有繁琐的模板参数,每个人都会更快乐。这是 IMO 更优雅,更易于使用:

#include <array>

template<class T, class ...Args>
struct first_arg{
    using type = T;
};

template<class ...Args>
using first_arg_t = typename first_arg<Args...>::type;

template<class ...Args>
auto lst(Args &&...args){
    return std::array<first_arg_t<Args...>, sizeof...(Args)>({ std::forward<Args>(args)... });
}

int main(){
    const auto a = lst(1, 2, 3, 4)[2];
    return 0;
}

我知道它没有明确使用初始化列表,但它似乎是对您问题的最佳答案。