我正在使用cppreference.com - Constraints and Concepts (Since C++20)中的示例学习 C++ 概念,我将在此处将其重现为:
template <typename T>
requires std::integral<T> || std::floating_point<T>
constexpr double average(std::vector<T> const &vec) {
const double sum = std::accumulate(vec.begin(), vec.end(), 0.0);
return sum / vec.size();
}
int main()
{
std::vector sVec { 1, 2, 3, 4, 5};
assert(average(sVec) == 3);
}
Run Code Online (Sandbox Code Playgroud)
我添加了 std::array 的情况:
template <typename T, int size> // add size
requires std::integral<T> || std::floating_point<T>
constexpr double average(const std::array<T, size> &arr) { // use std::array<T, size> &arr) instead
const double sum = std::accumulate(arr.begin(), arr.end(), 0.0);
return sum / arr.size();
}
int main()
{
std::array sArr { 1, 2, 3, 4, 5};
assert(average(sArr) == 3);
}
Run Code Online (Sandbox Code Playgroud)
现在编译出现错误:
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:65:19: error: no matching function for call to 'average(std::array<int, 5>&)'
65 | assert(average(sArr) == 3);
| ~~~~~~~^~~~~~
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:14:18: note: candidate: 'template<class T> requires (integral<T>) || (floating_point<T>) constexpr double average(const std::vector<T>&)'
14 | constexpr double average(const std::vector<T> &vec) {
| ^~~~~~~
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:14:18: note: template argument deduction/substitution failed:
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:65:19: note: 'std::array<int, 5>' is not derived from 'const std::vector<T>'
65 | assert(average(sArr) == 3);
| ~~~~~~~^~~~~~
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:22:18: note: candidate: 'template<class T, int size> requires (integral<T>) || (floating_point<T>) constexpr double average(const std::array<T, size>&)'
22 | constexpr double average(const std::array<T, size> &arr) {
| ^~~~~~~
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:22:18: note: template argument deduction/substitution failed:
C:\Users\Cheng\OneDrive\Documents\Proj\HackerRank\Cpp\concept_introduction.cpp:65:19: note: mismatched types 'int' and 'long long unsigned int'
65 | assert(average(sArr) == 3);
| ~~~~~~~^~~~~~
Build finished with error(s).
Run Code Online (Sandbox Code Playgroud)
为什么?
的第二个模板参数std::array是 astd::size_t而不是int。
将第一行:更改template <typename T, int size>
为:template <typename T, std::size_t size>
应该解决这个问题。模板类型必须匹配。
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |