Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the user-defined conversion function template cannot have a deduced return type?

Tags:

c++

What is the reason of the following rule, "a user-defined conversion function template cannot have a deduced return type."

struct S {
  operator auto() const { return 10; } // OK
  template<class T> operator auto() const { return 42; } // error
};
like image 342
cinemarter Avatar asked Dec 18 '22 15:12

cinemarter


1 Answers

Even if it was allowed, in the second line, there is nothing that depends on the template. It can't be called (what is the purpose of T in that case ?)

If you want to convert to a user defined type, then you'll do that: Let's say you have:

struct S
{
   template<typename T> operator T() { return T(42); }
};

That's clear and there is no need to deduce anything. You'd call this like this:

S s;
int v = s;
float f = s;

Please notice that, in that case, using auto instead of float in the code above would prevent the compiler to deduce the type (is it a float ? an int ? an Orange ?). The sentence above simply explains that.

like image 109
xryl669 Avatar answered May 28 '23 13:05

xryl669