fork(3) download
  1. #include <iostream>
  2. #include <type_traits>
  3. using namespace std;
  4.  
  5. template<typename FROM, typename TO>
  6. struct CopyConstImpl {
  7. using type = typename remove_const<TO>::type;
  8. };
  9.  
  10. template<typename FROM, typename TO>
  11. struct CopyConstImpl<const FROM, TO> {
  12. using type = typename add_const<TO>::type;
  13. };
  14.  
  15. template<typename FROM, typename TO>
  16. struct CopyConst {
  17. using type = typename CopyConstImpl<typename remove_reference<FROM>::type, TO>::type;
  18. };
  19.  
  20. struct Foo {
  21. auto bar() -> typename CopyConst<decltype(*this), int>::type& {
  22. return x;
  23. }
  24. int x = 5;
  25. };
  26.  
  27. int main() {
  28. static_assert(is_same<int&, decltype(declval<Foo>().bar())>::value,
  29. "Non-const foo.bar() result must yield a non-const reference");
  30. //static_assert(is_same<const int&, decltype(declval<const Foo>().bar())>::value,
  31. // "Const foo.bar() result must yield a const reference");
  32. const Foo foo;
  33. foo.bar();
  34.  
  35. return 0;
  36. }
Compilation error #stdin compilation error #stdout 0s 3336KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:33:10: error: passing ‘const Foo’ as ‘this’ argument of ‘CopyConst<Foo&, int>::type& Foo::bar()’ discards qualifiers [-fpermissive]
  foo.bar();
          ^
stdout
Standard output is empty