C++ concept member check type ambiquity with reference(C++概念成员检查类型与引用的不一致)
本文介绍了C++概念成员检查类型与引用的不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习C++概念,我有一个讨厌的问题:
我不知道如何区分成员变量是int
类型的变量和成员变量是int&
类型。
原因是我正在使用的检查使用的是instance.ember语法,而在C++中,它返回一个引用。
完整示例:
#include <iostream>
#include <concepts>
template<typename T>
void print(T t) {
std::cout << "generic" << std::endl;
}
template<typename T>
requires requires(T t){
{t.val} -> std::same_as<int&>;
}
void print(T t) {
std::cout << "special" << std::endl;
}
struct S1{
int bla;
};
struct S2{
int val = 47;
};
int x = 47;
struct S3{
int& val=x;
};
int main()
{
print(4.7);
print(S1{});
print(S2{});
print(S3{});
}
我希望print(S3{})
由一般情况处理,而不是特殊情况。
请注意,将我的requires
内容更改为:
{t.val} -> std::same_as<int>;
使S2
与模板不匹配,因此无法工作(如我所说,我认为C++中的成员访问返回一个引用)。
是否有解决此问题的方法?
推荐答案
这里的问题是,表达式概念检查在检查中使用decltype((e))
,而不是decltype(e)
(额外的圆括号)。
因为t.val
是int
类型的左值(表达式从来没有引用类型),所以decltype((t.val))
是int&
,正如您已经发现的那样。
相反,您需要显式使用Single-Paren语法:
template <typename T>
requires requires (T t) {
requires std::same_as<decltype(t.val), int&>;
}
void print(T t) {
std::cout << "special" << std::endl;
}
或
template <typename T>
requires std::same_as<decltype(T::val), int&>
这篇关于C++概念成员检查类型与引用的不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:C++概念成员检查类型与引用的不一致


猜你喜欢
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01