c – std :: is_arithmetic在泛型lambda内的int类型中返回false:未定义的行为?
作者:互联网
考虑:
#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来判断我是在处理数字而不是其他非算术类型,并相应地打印(或不打印)引号.
但由于某种原因,“返回”(通过:: value成员)的值为false,即使我传递了一个int(我确保通过首先使用gcc的cxxabi.h打印demangled类型来做到这一点) )
从输出中可以看出,这会导致int用引号打印.
我的问题是:为什么它返回假?这与通用lambda有什么关系吗?我可以修理吗?
我实际上是直接在Coliru测试这个,所以你可以假设那里使用的任何gcc版本(目前6.3.0).
解决方法:
你的问题是,尽管有type typeid
returns(int)你在lambda中的实际类型是int const&并且is_arithmetic不专门用于那种确切的类型. You can get the type you actually want with std::decay
or a combination of std::remove_const
and std::remove_reference
.
标签:boost-hana,c,c14,gcc,typetraits 来源: https://codeday.me/bug/20190828/1753536.html