无法使用 auto 来参数化true_type来检测 T::value()
Can't detect T::value() using auto to parametrize true_type
使用SFINAE,has_value_int<T>
和has_value_auto<T>
都试图检测类T
是否具有名为value
的static constexpr
函数。
- 使用
int
参数化true_type
,has_value_int<T>
适用于演示类CCD_ 9和CCD_ - 使用
auto
参数化true_type
,has_value_auto<T>
总是返回false
使用int
和使用auto
有什么区别,为什么auto
不起作用?
具体来说,为什么过载分辨率更喜欢match_auto(...)
而不是match_auto(int)
?
#include <iostream>
using namespace std;
// parametrize true_type
template <int> using true_int = true_type; // works
template <auto> using true_auto = true_type; // does not work
// detect if T::value() is a valid compile-time expression
template <class T> true_int<(T::value(), void(), 0)> match_int(int);
template <class T> true_auto<(T::value(), void(), 0)> match_auto(int);
template <class> false_type match_int(...); // sometimes called
template <class> false_type match_auto(...); // always called
template <class T>
static constexpr bool has_value_int = decltype(match_int<T>(0))::value;
template <class T>
static constexpr bool has_value_auto = decltype(match_auto<T>(0))::value;
template <class T>
void demo() {
cout << has_value_int<T> << "(int), " // sometimes false
<< has_value_auto<T> << "(auto)" << endl; // always false
}
int main() {
struct pass { static constexpr int value() { return 1; } };
using fail = float;
cout << "has_value<pass> = "; demo<pass>(); // 1(int), 0(auto)
cout << "has_value<fail> = "; demo<fail>(); // 0(int), 0(auto)
return 0;
}
EDIT:使用gcc 7.3.0编译。叮当作品也是如此。
没有区别;这是一个gcc错误,Barry报告为#86703。
作为一种变通方法,不要使用函数:
// detect if T::value() is a valid compile-time expression
template <typename T, typename = void> struct match_auto : std::false_type {};
template <typename T>
struct match_auto<T, std::void_t<true_auto<(T::value(), void(), 0)>>>
: std::true_type {};
template <class T> static constexpr bool has_value_auto = match_auto<T>::value;
相关文章:
- 使用CMake检测支持的C++标准
- 当套接字连接断开时检测C/C++Unix
- C/C++预处理器是否可以检测一些编译器选项
- WMI检测进程创建事件-c++
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 下面是我为检测链接列表中的循环而制作的代码
- 落砂模拟碰撞检测C++和SFML
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 为什么C++编译器没有检测到正确声明的类?
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 检测win32服务创建和删除的最佳方法
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 正在LLVM中检测整数比较条件
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 如何在鼠标挂钩过程中检测拖动
- 位移操作和位掩码未检测到重复字符
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 如何检测运算符[]是否适用于Type
- 如何在 Windows 上使用 GetSave文件名检测"Save as type:"组合框何时更改?