Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
In the code below why is the templated foobar called and not the non-templated version I expect the non-templated version to be called as it is a precise argument match w/ the exception of the const
C++
void foobar(const int&) { } // not called
template<typename U> void foobar(U&&) { } // called

int main()
{
		int i = 159;
		foobar(i);
		return 0;
}

Please allow me to elaborate This all began upon examing the std::optional<T> constructors via https://en.cppreference.com/w/cpp/utility/optional/optional[^] I found the usual copy constructor and a constructor documented as below
C++
template < class U = T >
constexpr optional( U&& value );

Further the docs page states as below
Quote:
This constructor does not participate in overload resolution unless std::is_constructible_v<t, u&&=""> is true and std::decay_t (until C++20)std::remove_cvref_t (since C++20) is neither std::in_place_t nor std::optional<t>.

Though this is mostly gobledegook to me as near as I can discern by virtue of the last statement to wit
Quote:
"... is neither ... nor std::optional<t>."

this constructor should not participate in overload resolution as I am utilizing C++20

Upon experimenting w/ my own class w/ all identical constructors as std::optional<T> I found the constructor w/ the above templated signature was invoked instead of the expected copy constructor If this is so what use is the copy constructor as it seems it will never be called Thank You Kindly

What I have tried:

Read docs Scratched head Neither helped
Posted
Comments
Peter_in_2780 16-Dec-21 21:35pm    
In your first example, the argument i to the constructor is int not const int. I don't know if this is relevant, but it would be easy enough to try.
BernardIE5317 16-Dec-21 21:58pm    
Thank You for your Kind interest Yes I have confirmed if i is declared const the expected foobar is called i.e. the first However I still do not understand why the same is not called even if i is not const - Kind Regards - Cheerio
[no name] 16-Aug-22 14:08pm    
How do you know the constrictor isn't called? Maybe you need to fill the constructor with at least one line of code and check again?
BernardIE5317 18-Aug-22 19:25pm    
As the post is quite old I do not recall the method by which I discerned which function was called. Perhaps I merely traced in the debugger but most probably via trace statements i.e. to wit in particular to be specific e.g. cout << __LINE__ << ' ' <<__FUNCSIG__ << endl; as that is my usual method however I probably did not include in post here as to not pollute the display with it as it is not necessary to the question. Rest assured I am certain of the function called. - Cheerio

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900