2

What I'm trying to achieve is something like this:

template<typename T>
void foo(T t) {
    TWithoutReferenceType t1 = Magic(t); //some magic here
}

TWithoutReference is the same type of T but without reference, so for example:

Magic(int i) -> int i
Magic(int& i) -> int i
Magic(int&& i) -> int i 

I don't know if this is possible for rvalue references or what it could mean in practice though.

WHY I NEED IT:

template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(const function<ReturnType(Args...)>& func)
{
    return ([=](Args... args) mutable {
        static map<tuple<Args...>, ReturnType> cache;
        tuple<Args...> t(args...);
        auto result = cache.insert(make_pair(t, ReturnType{}));
        ...

So for example if Args ... is vector<double> & and I change the order of the elements, the correspondent key in cache is changed also, and I don't want that this happens, so I don't want that a key change in the future as side effect.

Sorry if I posted the whole code, but I'm afraid that if I make it simpler I'll lose the point of the question.

justHelloWorld
  • 6,478
  • 8
  • 58
  • 138
  • Are you saying that you want `tuple` to be a tuple of non-reference types – M.M Apr 28 '16 at 04:23
  • Exactly. And I think that this is a duplicate of [this](http://stackoverflow.com/questions/12742877/remove-reference-from-stdtuple-members) question – justHelloWorld Apr 28 '16 at 04:25
  • OK, let us know if that solution worked for you and I'll close the question – M.M Apr 28 '16 at 04:26

2 Answers2

2

What you're finding is std::remove_reference:

If the type T is a reference type, provides the member typedef type which is the type referred to by T. Otherwise type is T.

Possible implementation

template< class T > struct remove_reference      {typedef T type;};
template< class T > struct remove_reference<T&>  {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};

You might implement Magic as

template <typename T> 
typename remove_reference<T>::type Magic(T t) { 
    return t; 
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

You have several choices including:

template <typename T>
typename std::remove_reference<T>::type Magic(const T& t) { return t; }

or

template <typename T>
typename std::remove_reference<T>::type Magic(T&& t) { return t; }
Jarod42
  • 203,559
  • 14
  • 181
  • 302