我试图重载[]
操作符,以便我可以访问std::tuple
的元素。由于某些原因,我得到以下错误:
prog.cpp:11:73:错误:函数体外部使用参数N
prog.cpp:11:73:错误:在函数体外使用参数N
prog.cpp: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);
}
如果有人能解释为什么会发生这种情况,以及我如何才能得到这个工作,这将是非常感激的。谢谢。
您正在尝试使用operator[]
的函数参数N
(在编译时不知道)作为std::tuple_element
的模板参数,必须在编译时知道。
模板参数N
是编译时的东西,而operator[]
参数N
只在运行时实现。编译器不知道N
是什么,所以不能把它当作模板参数。