2
votes

If i understood correctly, we have 3 cases in type deduction:

1) param is not reference nor pointer.

   int x = 5;
   template< typename T>
   func( T param ) 

   template< typename T>
   func1( T & param ) 

   func(x)
   func1(x)

in both cases T is deduced to be int

2) param is pointer or reference , in this case we ignore reference and pointer -ness

   template< typename T>
   func( T & param ) 

   int x = 5;
   const int y =x;
   const int &z =x;

   func(x) // param is type int & and T is type int 
   func(y) // param is type const int & and T is type const int
   func(z) // param is type const int & and T is type const int

3) param is "universal reference".

template< typename T>
func( T && param )

int x = 5;
const int y = x;
const int & z = x;
func(x) // param is type int & and T is type int &
func(y) // param is type const int & T is type const int &
func(z) // param is type const int & and T is type const int &
func(5) // param is type int && and T is type int &&

The auto keyword decides type like template deduction with the exception of

auto x = {1 , 2 , 3} where type of auto x is initalizer_list

However how does this work with constness? Having

struct Test{ int x };
Test t;
const Test & t1 = t;
auto t2 = t1; // t2 is type of Test not const Test &

For example if we passed

const int* const x = ...

In what cases would be constness ignored and what consntess would prevail?

1
func(5) // param is type int && and T is type int && - wrong. param is int&& while T is int. - StoryTeller - Unslander Monica
@yeputons: Incorrect, pointers can have qualification conversions. That is a special case. And since this question explicitly mentions const-ness, those qualification conversions should be part of the answer. - MSalters
you don't make much sense to me: your 3 types of deduction seem... confusing... 1st case: you say it's not a reference then you show a reference in the example. 2nd you say pointer and you show no pointer example and you say "we ignore pointer-ness" and I can't think of an interpretation of that statement that could be true. - bolov
try this: edit your answer by using the right terminology: parameter is when you declare/define a function, argument is what you provide to a function when you call it. For instance: void foo(int a) ; foo(b) here a is parameter, b is argument. And revisit that "pointer" shenanigan. I can't see a scenario when the pointer type is ignored in a deducing context. - bolov
Possible duplicate of Const in auto type deduction - xskxzr

1 Answers

0
votes

auto uses the same rules as template argument deduction:

From cppreference:

Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call

So, following your example:

struct Test{ int x };
Test t;
const Test & t1 = t;
auto t2 = t1; // t2 is Test
const auto t3 = t1; // t3 is const Test