fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <cassert>
  5. using namespace std;
  6.  
  7. struct A {
  8. A(int &&) { cout << "create A" << endl; }
  9. A(A&&) { cout << "move A" << endl; }
  10. ~A(){ cout << "kill A" << endl; }
  11. };
  12.  
  13. template <class T> struct B {
  14. T value;
  15. B() : value() { cout << "new B" << endl; }
  16. B(const T &__a) : value(__a) { cout << "create B" << endl; }
  17. B(const B &p) = default;
  18. B(B && o) = default;
  19. ~B(){ cout << "kill B" << endl; };
  20. template <class U, class = typename enable_if<is_convertible<U, T>::value>::type>
  21. B(U &&v) : value(std::forward<U>(v)) {
  22. cout << "new forward initialized B" << endl;
  23. }
  24. };
  25.  
  26. void foo(B<const A&> a){ cout << "Using A" << endl; }
  27.  
  28. template<typename T>
  29. void baz(const vector<B<T>> &test){
  30. cout << "In Baz: " << endl;
  31. for(const auto &e : test) std::cout << e.value << endl;
  32. }
  33.  
  34. int main(){
  35. cout << "Foo test case:" << endl;
  36. foo( {123} );
  37.  
  38. cout << "\nThis works as expexted::" << endl;
  39. foo( A(123) );
  40.  
  41. // passing strings around works
  42. cout << "\nString test case:" << endl;
  43. baz<std::string>({"Hello", "World"});
  44.  
  45. // passing const reference doesn't
  46. cout << "\nSecond string test case:" << endl;
  47. baz<const std::string &>({"Hello", "World"});
  48. }
  49.  
Runtime error #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Foo test case:
create A
new forward initialized B
kill A
Using A
kill B

This works as expexted::
create A
new forward initialized B
Using A
kill B
kill A

String test case:
new forward initialized B
new forward initialized B
In Baz: 
Hello
World
kill B
kill B
kill B
kill B

Second string test case:
new forward initialized B
new forward initialized B
In Baz: