1

I am watching Walter Brown's talk on CppCon 2014 'Modern Template Metaprogramming: A Compendium'. In part two, he demonstrates the usage of decltype and declval with a sample implementation of is_copy_assignable.

Here is a link to the video, with the slide, showing the source code (rewind a bit if you want to hear his explanations): https://youtu.be/a0FliKwcwXE?t=1576

Here I have typed his implementation in a sample program:

#include <iostream>
#include <type_traits>
#include <mutex>

using namespace std;


template <class T>
struct my_is_copy_assignable {
private:
    template<class U, class = decltype(declval<U&>() = declval<U const&>())>
    static true_type try_assignment(U&&);   // Why U&& and not for example U?

    static false_type try_assignment(...);

public:
    using type = decltype( try_assignment( declval<T>() ) );
};


int main()
{
    cout << "Is mutex copy assignable: " 
         << my_is_copy_assignable<mutex>::type() << endl
         << "Is int copy assignable: " 
         << my_is_copy_assignable<int>::type() << endl;

    return 0;
}

My question is about the function template (the commented one):

static true_type try_assignment(U&&);

Why he is using rvalue reference? I tried it with lvalue reference and even pass-by-value parameter and it seems to work.

What I am missing here?

  • Hints: 1: What are you checking if you pass a function argument to a by-value parameter? 2: And what value-categories are acceptable initializers to non-const lvalue references? – Johannes Schaub - litb Feb 19 '17 at 11:08
  • 1
    Being a template it might, or might not, deduce the parameter as an rvalue reference. [It depends](http://stackoverflow.com/questions/14302849/syntax-for-universal-references). – Bo Persson Feb 19 '17 at 11:55
  • What I am missing is the universal reference concept, which is very well explained in the link provided by @BoPersson Thanks for the help, guys! – Tsvetomir Dimitrov Feb 19 '17 at 14:50

0 Answers0