constant references with typedef and templates in c++

前端 未结 5 1433
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 13:45

I heard the temporary objects can only be assigned to constant references.

But this code gives error

#include     
template

        
5条回答
  •  悲哀的现实
    2020-11-28 14:02

    To maintain consistency with the Right Left Rule, I prefer to use 'cv' qualifiers like so.

    int const x = 2; // x is a const int (by applying Right Left rule)
    
    int const *p = &x;  // p is a pinter to const int
    

    In your example, I would write const ref error = check(); like so

    ref const error = check(); // parsed as error is a const reference to an integer
    

    As @Prasoon Saurav pointed out, cv qualifiers are ignored when introduced through typedef because as @GMan also says, that cv qualified references are ill-formed.

    Therefore the declaration is effectively as below, which of course is an error.

       int &error = check(); 
    

    Check out this for more information.

提交回复
热议问题