我可能在這里問了一個錯誤的問題,但是我到底做錯了什么,導致編譯器認為我對堆疊的pop方法所期望的約束是std::same_as<void, T>?
#include <concepts>
#include <stack>
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t)。
{ s.pop() } -> std::same_as<T>; //錯誤似乎源于此。
};
template <typename T, generic_stack< T> S>
void compile_if_stack(S){}。
int main() {}。
compile_if_stack<int>(std::stack<int>{})。
}
我嘗試了std::same_as<decltype(s.pop()), T>;,似乎可以作業,但我不明白的是前一種方法有什么問題。
完整的錯誤
$ clang -std=c 20 main.cpp
main.cpp:14:5: error: no matching function for call to ' compile_if_stack'
compile_if_stack<int>(std::stack<int>{})。
^~~~~~~~~~~~~~~~~~~~~
main. cpp:11:6: 注意:候選template被忽略。約束條件不滿足[with T = int, S = std::stack<int>]
void compile_if_stack(S) {}。
^
main.cpp:10:23: 注意:因為'generic_stack<std::stack<int>, int>'評估為false。
template <typename T, generic_stack< T> S>
^
main.cpp:7:25: 注意:因為型別約束'std::same_as<void, int> '被未滿足。
{ s.pop() } -> std::same_as<T>; //錯誤似乎源于此。
^
/usr/bin/.../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/..././include/c /11.1。 0/concepts:63:19: 注意:因為'__detail::__same_as<void, int>'評估為false。
= __detail::__same_as<_Tp, _Up> && __detail::__same_as<_Up, _Tp> 。
^
/usr/bin/.../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/..././include/c /11.1。 0/concepts:57:27: 注意:因為'std::is_same_v<void, int>'評估為false。
概念 __same_as = std::is_same_v<_Tp, _Up> 。
^
1錯誤生成。
來自GCC 11.1.0的C 編譯器出現了語意相同的錯誤資訊。
uj5u.com熱心網友回復:
這是因為stack.pop()回傳void,根據std::stack::pop的記載。
這個約束是不對的,你應該檢查top,而不是:
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t)。
{ s.top() } -> std::same_as<T const& >。
};
uj5u.com熱心網友回復:
std::stack不會在pop上回傳一個值。它有一個單獨的函式用于此。也就是說,top。所以pop()是一個void函式。因此出現了錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315758.html
標籤:
