std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
std::is_arithmetic returns false for int type inside generic lambda: Undefined behavior?
考虑:
#include <iostream>
#include <typeinfo>
#include <type_traits>
#include <cxxabi.h>
#include <boost/hana.hpp>
namespace hana = boost::hana;
struct Person {
BOOST_HANA_DEFINE_STRUCT(Person,
(std::string, name),
(int, age)
);
};
template<typename T>
void stringify(const T& v) {
hana::for_each(hana::accessors<T>(), [&v](auto a) {
// Here I'm printing the demangled type, just to make sure it is actually the type I'm thinking it is.
std::cout << abi::__cxa_demangle(typeid(decltype(hana::second(a)(v)){}).name(), 0, 0, 0);
// If the value is arithmetic, "quote" should be an empty string. Else, it should be an actual quote.
// UNEXPECTED BEHAVIOR IS HERE
std::string quote{(std::is_arithmetic<decltype(hana::second(a)(v))>::value?"":""")};
// Finally do what we're here for.
std::cout << " " << hana::first(a).c_str() << " = " << quote << hana::second(a)(v) << quote << "n";
});
}
int main() {
Person john;
john.name = "John Doe";
john.age = 42;
stringify(john);
}
现场观看
输出:
std::__cxx11::basic_string</*...*/> name = "John Doe"
int age = "42"
我试图使用std::is_arithmetic
来判断我是否正在处理一个数字而不是其他一些非算术类型,并相应地打印(或不打印)一个引号。
但是出于某种原因,即使我传递了一个int
,"返回"的值(通过::value
成员)也是false
(我确保我通过首先使用 gcc 的cxxabi.h
打印拆解类型来正确执行此操作)
从输出中可以看出,这会导致int
打印带有引号。
我的问题是:为什么它返回假?这与通用 lambda 有什么关系吗?我可以修复它吗?
我实际上是直接在 Coliru 上测试的,所以你可以假设那里使用的任何 gcc 版本(目前为 6.3.0)。
您的问题是,尽管返回的类型typeid
(int),但 lambda 中的实际类型是int const&
的,is_arithmetic
不是专门针对该确切类型的。您可以使用std::decay
或std::remove_const
和std::remove_reference
的组合获得您真正想要的类型。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- 将 false 转换为指针类型 void*
- 具有自定义返回类型和"false"返回条件的函数?
- 什么类型会使"std::has_unique_object_representations"返回 false?
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- 为什么没有int或false的数据类型
- 函数在另一个函数中调用时返回 false,而单个返回类型为 true
- 将我自己的对象添加到 QComboBox,Q_DECLARE_METATYPE,不完整的类型'QStaticAssertFailure<false>'
- 如果数据类型为整数值或双数值,则当c++返回true/false时
- C++中的内置类型bool或C中的stdbool.h类型将TRUE和FALSE定义为不是机器字的大小
- boost::proto::is_aggregate为聚合类型时返回false
- unordered_map的默认构造函数,bool类型将设置为false
- double比较类型的变量总是返回false
- 在 QGlobal.h 上对不完整的类型 'QStaticAssertFailure<false>' 'sizeof'应用无效