Function template with return type T does not compile

The following code compiles fine:

template<typename T> void f(const T &item) { return; } int main() { f("const string literal"); } 

Compilation succeeded in ideon: http://ideone.com/dR6iZ

But when I mention the return type, it does not compile:

 template<typename T> T f(const T &item) { return item; } int main() { f("const string literal"); } 

Now it gives an error:

prog.cpp: 6: error: there is no corresponding function to call the function "f (const char [21])

Code in ideone: http://ideone.com/b9aSb

Even if I make the return type const T , it does not compile .

My question is:

  • Why doesn't it compile?
  • What is the return type for the error and creating the function template?
+4
source share
2 answers

You cannot return an array from a function, so template creation is not performed, and there is no corresponding function.

You get this specific error due to SFINAE - This is not an error that the compiler cannot create your function, it is an error, there is no corresponding function.

You can return an array reference - T const & will be returned.

EDIT: in response to comments:

Firstly, this is really a worthy example of SFINAE.

 template<typename T> T f(const T &item) { return item; } char const * f(void const * item) { return 0; } int main() { f("abc"); } 

When the compiler compiles this, it will first try to instantiate the template f to create an exact match for the type const char [3] . Due to these reasons, this fails. Then he selects an inaccurate match, the usual function, and when you turn the call const char [3] - a const char * .

+13
source

it looks like you are telling him that you plan to return T, but then you really return const T &. maybe try changing the ad:

 template<typename T> const T& f(const T& item) { return item; } 

or perhaps change the return value to a dereferenced version of the argument:

 template<typename T> T f(const T& item) { return (*item); } 
0
source

Source: https://habr.com/ru/post/1343710/


All Articles