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

标签 c++ templates boost-hana

我刚刚阅读了 Boost.Hana tutorial但不幸的是很早就卡住了。谁能向我解释为什么整数的 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) {}

关于c++ - Boost.Hana JSON 示例:string 和 decltype(std::to_string(...)) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415087/

相关文章:

c++ - 这个 bool 变量是如何工作的?

c++ - 查看C++编译后生成的指令大小?

c++ - 错误 : invalid conversion from "const ..." to "..." error message when using templates

c++ - 如何查询一个类型是否为models Struct?

c++ - boost::hana 如何检查类型是否为 std::optional?

c++ - 内存中的多重映射表示

c++ - 在 C++/Qt 中作为 lambda 函数参数的槽

c++ - 别名模板特化

c++ - 我可以在编译时使用一个常量来选择一个类,可能使用模板吗?

c++ - 使用 boost.hana 内省(introspection)结构定义