我刚刚阅读了 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/