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.

3
  • Are you saying that you want tuple<Args...> to be a tuple of non-reference types Commented Apr 28, 2016 at 4:23
  • Exactly. And I think that this is a duplicate of this question Commented Apr 28, 2016 at 4:25
  • OK, let us know if that solution worked for you and I'll close the question Commented Apr 28, 2016 at 4:26

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

So can you write the function that I'm look for using std::remove_reference please?
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; } 

6 Comments

you probably want typename std::remove_reference<T>::type as the return type in the second one.
@M.M Isn't it the same thing?
@songyuanyao: Not if you provide the template parameter, i.e: Magic<const int&>(my_int);, but that change nothing for Magic(my_int);
@Jarod42 Sorry didn't get it. I meant typename std::remove_reference<T>::type and std::remove_reference_t<T> is the same thing, isn't it?
There are the same but remove_reference_t is only available since c++14 (and OP's tag is c++11).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.