Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify template has_field with C++17/20

Tags:

c++

templates

Given next working solution:

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;

Idea was taken from https://stackoverflow.com/a/14523787/3743145

I wonder if there a C++17/20 more laconic way to achieve same effect. Like

template<typename T>
constexpr bool has_value = .....;

Usage:

template<typename T>
enable_if_t<has_value<T>,
std::ostream&> operator<<(std::ostream& os, T const& arg)
{
    return os << arg.value;
}
like image 663
kyb Avatar asked Mar 12 '20 06:03

kyb


2 Answers

If C++20 is on the table, you can do that with a concept that checks a simple requirement

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;
}

T::value being a well formed expression is being checked in the requires expression. Pretty straight forward to write, and to use as a constraint on a template.

like image 80
StoryTeller - Unslander Monica Avatar answered Sep 22 '22 23:09

StoryTeller - Unslander Monica


In c++17

template<typename,typename=void> constexpr bool has_value = false;
template<typename T>             constexpr bool has_value<T,decltype(T::value,void())> = true;

Test

struct V { int value; };
struct W { int walue; };

static_assert(has_value<V>);
static_assert(not has_value<W>);

Thanks to https://stackoverflow.com/a/52291518/3743145

like image 36
kyb Avatar answered Sep 23 '22 23:09

kyb