std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?

std::is_arithmetic returns false for int type inside generic lambda: Undefined behavior?

本文关键字:false 类型 未定义 返回 int lambda is arithmetic std 中的      更新时间:2023-10-16

考虑:

#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::decaystd::remove_conststd::remove_reference的组合获得您真正想要的类型。