为什么在约束中找到模板,而不是函数? C++ 20
我正在学习C ++ 20个概念和约束,但我不明白为什么在这种情况下被认为是未定义的,但它似乎在需要
子句中工作正常。这里怎么了?为什么?
如果我删除了分号,则编译器说u不是模板
error: expected unqualified-id before ‘;’ token
11 | requires std::integral<T> || std::floating_point<T>;
| ^
main.cpp:12:28: error: ‘T’ was not declared in this scope
12 | constexpr double average(U<T> const &it) {
#include <numeric>
#include <vector>
#include <iostream>
#include <concepts>
template <typename T, std::forward_iterator U>
requires std::integral<T> || std::floating_point<T>;
constexpr double average(U<T> const &it) {
const double sum = std::accumulate(it.begin(), it.end(), 0.0);
return sum / it.size();
}
int main() {
std::vector ints { 1, 2, 3, 4, 5};
std::cout << average(ints) << '\n';
}
I'm learning about C++20 concepts and constraints and I don't understand why in this case T is considered undefined, yet it seems to work fine in the requires
clause. What's wrong here? and why?
If I remove the semicolon, the compiler says U is not a template
error: expected unqualified-id before ‘;’ token
11 | requires std::integral<T> || std::floating_point<T>;
| ^
main.cpp:12:28: error: ‘T’ was not declared in this scope
12 | constexpr double average(U<T> const &it) {
#include <numeric>
#include <vector>
#include <iostream>
#include <concepts>
template <typename T, std::forward_iterator U>
requires std::integral<T> || std::floating_point<T>;
constexpr double average(U<T> const &it) {
const double sum = std::accumulate(it.begin(), it.end(), 0.0);
return sum / it.size();
}
int main() {
std::vector ints { 1, 2, 3, 4, 5};
std::cout << average(ints) << '\n';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请阅读有关 Container Concept 完整的解决方案。这是仅仅显示方向的部分解决方案。
please read about container concept for the full solution. here is a partial solution just to show a direction.