【发布时间】:2019-08-13 20:17:28
【问题描述】:
以下code
#include <iostream>
#include <initializer_list>
using namespace std;
constexpr initializer_list<int> list = {1, 2, 3};
template<const int* begin, const int* end>
bool contains(int v)
{
if constexpr(begin != end)
{
if (*begin = v)
return true;
else
return contains<next(begin), end>(v);
}
return false;
}
int main()
{
cout << contains<list.begin(), list.end()>(2);
return 0;
}
产生一些非常奇怪的错误信息:
main.cpp: In function 'int main()':
main.cpp:25:49: error: no matching function for call to 'contains<list.std::initializer_list<int>::begin(), list.std::initializer_list<int>::end()>(int)'
cout << contains<list.begin(), list.end()>(2);
^
main.cpp:10:6: note: candidate: 'template<const int* begin, const int* end> bool contains(int)'
bool contains(int v)
^~~~~~~~
main.cpp:10:6: note: template argument deduction/substitution failed:
main.cpp:25:49: error: the address of '._86' is not a valid template argument
cout << contains<list.begin(), list.end()>(2);
^
main.cpp:25:49: error: 'list.std::initializer_list<int>::end()' is not a valid template argument for 'const int*' because it is not the address of a variable
我相信这个可以编译,因为编译器在编译时拥有所有信息:list 是 constexpr,它的 begin、end 和 next 也是如此。那么是什么阻止了它的工作呢?
【问题讨论】:
标签: c++ templates c++17 constexpr