constant references with typedef and templates in c++ -


I have heard that temporary objects can only be specified in continuous references.

But this code error

  #include & lt; Iostream.h & gt; Template & lt; Class t & gt; T const & amp; Check () {Return T (); // Return a floating object) int main (int argc, char ** argv) {const int and resCheck = check & lt; Int & gt; (); / * OK * / Typingfte & amp; Referee; Const Ref: error = check & lt; Int & gt; (); / * Error * / return 0; }  

which is the error type 'int & amp;' Invalid introduction type 'const int' for reference of

with this expression :

  typingf int & amp; Referee; Constant Reef Error;  

It does not do that you think it does. Instead, consider:

  typedef int * indicator; Typing conferencing pointer const_pointer;  

const_pointer type int * const , no const int * . That is, when you say that const T is saying "make a type where T is immutable"; So in the previous example, the indicator (not point) has been made irreversible.

The reference can not be made to const or unstable . It:

  int & amp; Constx;  

is meaningless, so adding CV-qualifiers does not have any effect in the references.

Therefore, in error type int & amp; . You can call it const int & amp; can not specify.


There are other problems with your code. For example, this is definitely false:

  template & lt; Class t & gt; T const & amp; Check () {Return T (); // Return a floating object}  

What you're doing here is a temporary object which returns the return of the function returning the function This is the case, if you use it, it is undefined behavior because there is no object in context, it is not better than this:

  template & lt; Class t & gt; T const & amp; Check () {t x = t (); Return x; // A local withdrawal ... bang you are dying}  

A better test will be:

  template & lt; Class T & gt; T check () {return t (); }  

The return rendering function is temporary, so you can still test that you can force temporarily continuous references.


Comments