Nan Xiao
Nan Xiao

Reputation: 17477

How to understand "MoveOnCopy(T&&) -> MoveOnCopy<T>" definition?

I come across following C++ code:

// Struct: MoveOnCopy
template <typename T>
struct MoveOnCopy {

  MoveOnCopy(T&& rhs) : object(std::move(rhs)) {}
  MoveOnCopy(const MoveOnCopy& other) : object(std::move(other.object)) {}

  T& get() { return object; }

  mutable T object; 
};

template <typename T>
MoveOnCopy(T&&) -> MoveOnCopy<T>;

I am a little confused about following statement:

template <typename T>
MoveOnCopy(T&&) -> MoveOnCopy<T>;

And just guess its a function definition which returns a MoveOnCopy struct. I checked C++11, C++14 and C++17, but can't find similar example. Could anyone help to elaborate this definition?

Upvotes: 0

Views: 86

Answers (1)

Brian Bi
Brian Bi

Reputation: 119372

That's a C++17 deduction guide. It tells the compiler how to deduce the template argument for MoveOnCopy from constructor arguments. For example, in:

MoveOnCopy m(123);

an object of type MoveOnCopy<int> will be constructed.

See here for more details.

Upvotes: 1

Related Questions