为什么我会"在函数体外使用参数'N'?"

tem*_*boy 1 c++ c++11

我正在尝试重载[]运算符,以便我可以访问a的元素std::tuple.出于某种原因,我收到以下错误:

prog.cpp:11:73:错误:在函数体
prog.cpp 外使用参数'N' :11:73:错误:在函数体
prog.cpp 外使用参数'N' :11:73:错误:使用参数'N'在函数体外部
prog.cpp:11:89:错误:模板参数1无效

很奇怪,因为大多数都是第一次重复.而且我不明白为什么我得到那个错误,因为不是因为我们可以使用参数作为返回类型而不是返回类型的全部内容?

#include <tuple>

template <class... Args>
struct type_list
{
    std::tuple<Args...> var;

    type_list(Args&&... args) : var(std::forward<Args>(args)...) {}

    auto operator[](std::size_t const N) -> typename std::tuple_element<N, std::tuple<Args...>>::type&&
    {
        return std::get<N>(var);
    }
};

int main()
{
    type_list<int, int, bool> array(2, 4, true);
}
Run Code Online (Sandbox Code Playgroud)

如果有人能够解释为什么会发生这种情况以及如何让它发挥作用,那将非常感激.谢谢.

Dav*_*own 5

您正在尝试使用该函数的参数Noperator[](未在编译时已知)作为模板论据std::tuple_element必须在编译时是已知的.

  • @templateboy:因为我可以写`size_t i; cin >> i; cout << yourobject [i];`编译器在那里使用哪个`operator <<`重载? (4认同)