fork download
  1.  
  2. #include <iostream>
  3. #include <typeinfo>
  4.  
  5. int* returnsPointer() { return nullptr; }
  6. int& returnsRef() { static int a; return a; }
  7. int returnsValue() { return 10; }
  8.  
  9. template<typename> void printType();
  10. template<> void printType<int>()
  11. {
  12. std::cout << "int\n";
  13. }
  14.  
  15. template<> void printType<int*>()
  16. {
  17. std::cout << "int*\n";
  18. }
  19.  
  20. template<> void printType<int&>()
  21. {
  22. std::cout << "int&\n";
  23. }
  24.  
  25. int main()
  26. {
  27. // similar D behavior in C++:
  28.  
  29. auto d_pointer = returnsPointer();
  30. auto d_ref = returnsRef();
  31. auto d_ref2 = &returnsRef();
  32. auto d_value = returnsValue();
  33.  
  34. printType<decltype(d_pointer)>();
  35. printType<decltype(d_ref)>();
  36. printType<decltype(d_ref2)>();
  37. printType<decltype(d_value)>();
  38.  
  39. std::cout << "--------------------\n";
  40.  
  41. // desired C++ behavior to have in D:
  42.  
  43. auto* c_pointer = returnsPointer();
  44. // auto* c_ref = returnsRef(); // error can't compile this (desired behavior here)
  45. auto* c_ref2 = &returnsRef();
  46. // auto* c_value = returnsValue(); // error can't compile this
  47.  
  48. printType<decltype(c_pointer)>();
  49. printType<decltype(c_ref2)>();
  50.  
  51. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
int*
int
int*
int
--------------------
int*
int*