Jes
Jes

Reputation: 2684

template specialization with struct in c++14

I am trying to write a specialized decay with template specialization on certain types:

template <typename T>
struct stateful_decay {
  using type = T;
};

template <typename T>
struct stateful_decay<T&&> {
  using type = T;
};

template <>
struct stateful_decay<PullTask&&> {
  using type = PullTask;
};

template <>
struct stateful_decay<PullTask&> {
  using type = PullTask;
};

template <>
struct stateful_decay<PullTask> {
  using type = PullTask;
};

template <>
struct stateful_decay<const PullTask&&> {
  using type = PullTask;
};
template <>
struct stateful_decay<const PullTask&> {
  using type = PullTask;
};

template <>
struct stateful_decay<const PullTask> {
  using type = PullTask;
};

template <typename T>
using stateful_decay_t = typename stateful_decay<T>::type;

Apparently, PullTask specialization has a lot of verbosity. Basically, any thing related to PullTask type should decay to PullTask. Is there any way to improve this? I am thinking about to use std::decay_t but didn't know how to do so.

Upvotes: 0

Views: 62

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

#include <type_traits>

template <typename T>
struct stateful_decay
    : std::conditional<std::is_same<PullTask, std::decay_t<T>>{}, PullTask, T> {};

template <typename T>
struct stateful_decay<T&&>
    : stateful_decay<T> {};

template <typename T>
using stateful_decay_t = typename stateful_decay<T>::type;

DEMO

Upvotes: 1

Related Questions