WLGBC 好吧,我突然想明白了,自问自答一波
template<typename T>
requires std::integral<std::remove_reference_t<T>>
void f(T&& t)
{
std::cout << std::boolalpha << std::is_same<T&&, int&&>() << '\n';
}
int main() {
int t = 10;
f(10); // OK
f(std::move(t)); // OK
f(t); // Error
}
只要让T套上std::remove_reference_t<>就好了,去除引用就能判断了,万能引用也没有失效,只是int&
不符合泛型约束
题外话:
不得不说Clang的提示是最人性化的,MSVC提示过于简略,GCC提示略显复杂
MSVC
1>C:\dev\CppProject1\CppProject1\源.cpp(22,8): error C2672: “f”: 未找到匹配的重载函数
1>C:\dev\CppProject1\CppProject1\源.cpp(13,6): message : 可能是“void f(T &&)”
1>C:\dev\CppProject1\CppProject1\源.cpp(22,5): message : “f”: 未满足关联约束
1>C:\dev\CppProject1\CppProject1\源.cpp(13): message : 参见“f”的声明
GCC(MinGW)
1.cpp: In function 'int main()':
1.cpp:14:10: error: no matching function for call to 'f(int&)'
14 | f(t); // Error
| ~^~~
1.cpp:6:6: note: candidate: 'template<class T> requires integral<T> void f(T&&)'
6 | void f(T&& t){
| ^
1.cpp:6:6: note: template argument deduction/substitution failed:
1.cpp:6:6: note: constraints not satisfied
In file included from 1.cpp:1:
c:\users\hex57\scoop\apps\mingw-winlibs\current\include\c++\12.2.0\concepts: In substitution of 'template<class T> requires integral<T> void f(T&&) [with T = int&]':
1.cpp:14:3: required from here
c:\users\hex57\scoop\apps\mingw-winlibs\current\include\c++\12.2.0\concepts:100:13: required for the satisfaction of
integral<T>' [with T = int&]
c:\users\hex57\scoop\apps\mingw-winlibs\current\include\c++\12.2.0\concepts:100:24: note: the expression 'is_integral_v<_Tp> [with _Tp = int&]' evaluated to 'false'
100 | concept integral = is_integral_v<_Tp>;
| ^~~~~~~~~~~~~~~~~~
Clang(MSVC)
1.cpp:14:2: error: no matching function for call to 'f'
f(t); // Error
^
1.cpp:6:6: note: candidate template ignored: constraints not satisfied [with T = int &]
void f(T&& t){
^
1.cpp:5:14: note: because 'int &' does not satisfy 'integral'
requires std::integral<T>
^
C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.34.31932\include\concepts:81:20: note: because
'is_integral_v<int &>' evaluated to false
concept integral = is_integral_v<_Ty>;
^
1 error generated.