Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this implementation of std::decay a correct one

Tags:

c++

templates

Is this implementation of std::decay a correct one?

template<class T>
T DecayType(T);

template<class T>
struct decay {
    using type = decltype(DecayType(declval<T>()));
};

I ask because everything I came across uses some template branching to carefully manipulate the type while this seems to be acting just by definition.

like image 851
unkulunkulu Avatar asked Jul 22 '15 14:07

unkulunkulu


2 Answers

Forming a function call like that requires passing by value, which requires a copy/move constructor. That implementation is not general enough.

It is the gist of what std::decay does, though.

like image 122
Potatoswatter Avatar answered Oct 08 '22 18:10

Potatoswatter


No, it's not correct, for the reasons Potatoswatter gave. In addition to requiring a copy/move constructor to return by value, you can't return some types by value at all:

#include <type_traits>

template<class T>
T DecayType(T);

template<class T>
struct decay {
    using type = decltype(DecayType(std::declval<T>()));
};

struct abstract { virtual void f() = 0; };

static_assert(std::is_same<decay<abstract&>::type, abstract>::value, "");

struct incomplete;

static_assert(std::is_same<decay<incomplete&>::type, incomplete>::value, "");

struct immortal { ~immortal() = delete; };

static_assert(std::is_same<decay<immortal&>::type, immortal>::value, "");
like image 34
Jonathan Wakely Avatar answered Oct 08 '22 17:10

Jonathan Wakely