Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overload Resolution, userdefined conversion and function template

With g++ 3.4 and 4.7 I observed the following strange behavior:

A function template does not match if a user defined conversion is necessary, where a plain function will. I could not find the corresponding rule in the C++98 Standard. Is g++ correct, (as I assume)? Or is it a bug?

template <class T>
int x(auto_ptr_ref<T> p)
{
  return 1;
}
// this would match
/*
int x(auto_ptr_ref<int> p)
{
   return 2;
}
*/
void dummy()
{
  cout << x(auto_ptr<int>()) << endl;
}
like image 852
koraxkorakos Avatar asked Jul 19 '16 06:07

koraxkorakos


People also ask

Can the function templates be overloaded?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

How do a function call gets matched to a set of overloaded functions?

When a function call is made to an overloaded function, the compiler steps through a sequence of rules to determine which (if any) of the overloaded functions is the best match. At each step, the compiler applies a bunch of different type conversions to the argument(s) in the function call.

What is overload resolution?

The process of selecting the most appropriate overloaded function or operator is called overload resolution. Suppose that f is an overloaded function name. When you call the overloaded function f() , the compiler creates a set of candidate functions.


1 Answers

GCC is correct, template argument deduction doesn't consider implicit conversions.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

For your code, auto_ptr_ref doesn't match against auto_ptr, the deduction of template parameter T fails, so the function template x() won't be considered for overload resolution at all.

like image 159
songyuanyao Avatar answered Sep 19 '22 01:09

songyuanyao