Boost.Hana JSON 示例:字符串和 decltype(std::to_string(..))之间的区别

Boost.Hana JSON example: Difference between string and decltype(std::to_string(...))

本文关键字:string Hana 之间 区别 to std 字符串 JSON decltype Boost 示例      更新时间:2023-10-16

我刚刚阅读了Boost.Hana教程,但不幸的是很早就卡住了。谁能向我解释为什么整数的to_json是这样实现的:

template <typename T>
auto to_json(T const& x) -> decltype(std::to_string(x)) {
return std::to_string(x);
}

我以为返回类型将简单地等同于std::string但事实并非如此。如果将其替换为std::string编译器会抱怨函数调用不明确。std::string 和 decltype(std::to_string(x(( 有什么区别?

这是因为 SFINAE 适用于返回类型的表达式。

并非所有类型都可以发送到std::to_string。这使得返回类型的表达式解析为无法使用提供的参数调用的函数。这是一个替换失败,会触发SFINAE,并且念珠菌被丢弃。

当将返回类型更改为std::string时,即使std::to_string(x)不会编译,也不会丢弃重载,因此该函数仍然参与重载集,使调用不明确。


您还可以在其他地方放置约束。以下是一些示例:

template<typename T> // in the non traitling return type
decltype(constrait) to_json() {}
// in the template parameters
template<typename T, decltype(void(constraint), 0) = 0>
auto to_json() -> std::string {}
// (less common) in the function parameters
template<typename T>
auto to_json(decltype(void(constraint), 0) = 0) {}