【发布时间】:2018-09-25 01:16:28
【问题描述】:
我正在尝试获取列表的第二个元素,但出现错误:
||=== Build: Debug in hellocpp17 (compiler: GNU GCC Compiler) ===|
/home/idf/Documents/c++/hellocpp17/main.cpp||In function ‘int main()’:|
/home/idf/Documents/c++/hellocpp17/main.cpp|67|error: no matching function for call to ‘Get<2>::Get(std::__cxx11::list<unsigned int>&)’|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: candidate: constexpr Get<2>::Get()|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: candidate expects 0 arguments, 1 provided|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: candidate: constexpr Get<2>::Get(const Get<2>&)|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: no known conversion for argument 1 from ‘std::__cxx11::list<unsigned int>’ to ‘const Get<2>&’|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: candidate: constexpr Get<2>::Get(Get<2>&&)|
/home/idf/Documents/c++/hellocpp17/main.cpp|40|note: no known conversion for argument 1 from ‘std::__cxx11::list<unsigned int>’ to ‘Get<2>&&’|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
程序:
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
template<unsigned n>
struct Get
{
template<class X, class...Xs>
constexpr auto operator()(X x, Xs...xs)
{
if constexpr(n > sizeof...(xs) )
{
return;
}
else if constexpr(n > 0)
{
return Get<n-1> {}(xs...);
}
else
{
return x;
}
}
};
int main()
{
list<unsigned> l = { 7, 5, 16, 8 };
unsigned l2 = Get<2>(l);
cout << l2 << endl;
return 0;
}
编辑 1
如果我实例化一个Get<2>,编译器会报这个错误
unsigned l2 = Get<2>()(l);
/home/idf/Documents/c++/hellocpp17/main.cpp|67|error: void value not ignored as it ought to be|
【问题讨论】:
-
你需要实例化
struct Get<2>-- 使用unsigned l2 = Get<2>()(l) -
@Fred 错误:/home/idf/Documents/c++/hellocpp17/main.cpp|67|错误: void 值不应被忽略|
-
当你应该将多个参数传递给
Get<2>()时,你也传递了一个std::list<unsigned int>。
标签: c++ c++17 variadic-templates template-meta-programming constexpr