C++14

Consider the following code:

void f(const int &) { cout << 1; }
void f(int&&) { cout << 2; }

template<typename T>
void g(const T&) { cout << 1; }
template<typename T>
void g(T&&) { cout << 2; }

int main()
{
  f(1);
  g(1);

  int i;
  f(i);
  g(i);
}

What will the code print? The answer is “2212,” which can be quite surprising.

But what if we really want a templated function that accepts r-value references? It turns out to be somewhat complicated (I think this works):

template<typename T>
typename enable_if<!is_lvalue_reference<T>::value, void>::type
g(T&&) { cout << 2; }

Now the output is “2211,” as “expected.”

Just as I thought I had a reasonable understanding of these things, I read about new features in C++14. Recall that you often do the following in C++:

auto x = my_function();

Now, you can do the following in C++14:

decltype(auto) x = my_function();

They do almost the same thing. The second one keeps x a reference, if possible. C++ is getting complicated.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s