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

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

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

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

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

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

并非所有类型都可以发送到 std::to_string。这使得 return 类型的表达式解析为无法使用提供的参数调用的函数。这是替换失败,触发 SFINAE,候选人被丢弃。

将return类型改为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) {}