鉴于下一个工作解决方案:
template<typename T, typename = void>
struct has_value_t : std::false_type { };
template<typename T>
struct has_value_t<T, decltype(T::value, void())> : std::true_type { };
template<typename T>
constexpr bool has_value = has_value_t<T>::value;
Run Code Online (Sandbox Code Playgroud)
我想知道是否有 C++17/20 更简洁的方法来实现相同的效果。喜欢
template<typename T>
constexpr bool has_value = .....;
Run Code Online (Sandbox Code Playgroud)
用法:
template<typename T>
enable_if_t<has_value<T>,
std::ostream&> operator<<(std::ostream& os, T const& arg)
{
return os << arg.value;
}
Run Code Online (Sandbox Code Playgroud)
如果 C++20 在桌面上,您可以使用检查简单需求的概念来做到这一点
template <typename T>
concept has_value = requires(T) {
T::value;
};
template<typename T> requires has_value<T>
std::ostream& operator<<(std::ostream& os, T const& arg)
{
return os << arg.value;
}
Run Code Online (Sandbox Code Playgroud)
T::value
在 requires 表达式中检查是一个格式良好的表达式。编写起来非常简单,并用作模板的约束。