Why do you define "negate()" as auto right after the template? Also, why are you returning "-f()" with a function specifier? You don't declare it as a function anywhere in the program. You are correct as to which function has priority (see code below).
#include <iostream>
int negate (int i)
{
return -i;
}
template <class F>
// Defined return type as F because that is the generic type
// defined by the template
F negate (F num)
{
// This subtracts one to test which function takes priority
return -num - 1;
}
int main()
{
int num = 2;
int num2 = negate (num); // call to int function
int num3 = negate<int> (num); // call to template function
std::cout << num2 << std::endl; // outputs -2
std::cout << num3 << std::endl; // outputs -3
return 0;
}
The int function took priority when the call was ambiguous. Was this what you were trying to do?
RicoJ, what compiler/version are you using? Compiles for me. Maybe explicitly pick C++14 or beyond as the language standard.
When I compile with just C++11, I get
4:16: note: deduced return type only available with -std=c++1y or -std=gnu++1y
Hmm. When I used namespace std in Furry Guy's code, I got these errors:
test1.cc:5:13: error: 'auto' not allowed in function prototype
auto negate(auto f)
^~~~
test1.cc:12:12: error: no viable constructor or deduction guide for deduction of
template arguments of 'negate'
cout << negate(1.1) << '\n';
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:639:29: note:
candidate template ignored: could not match 'negate<_Tp>' against 'double'
struct _LIBCPP_TEMPLATE_VIS negate : unary_function<_Tp, _Tp>
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:639:29: note:
candidate function template not viable: requires 0 arguments, but 1 was
provided
test1.cc:14:12: error: no viable constructor or deduction guide for deduction of
template arguments of 'negate'
cout << negate(-2) << '\n';
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:639:29: note:
candidate template ignored: could not match 'negate<_Tp>' against 'int'
struct _LIBCPP_TEMPLATE_VIS negate : unary_function<_Tp, _Tp>
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:639:29: note:
candidate function template not viable: requires 0 arguments, but 1 was
provided
3 errors generated.
The first one is because my compiler doesn't support that particular C++20 functionality, but I'm not sure about the others.
Yeah, when I removed namespace std, it got rid of those last two errors. I think its a namespace std issue.
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
using std::getline;
// etc etc etc
Takes up a little more space than "using namespace std" (and TBH I'd just use std:: if my program had fewer than about 10 cout objects), but it won't cause you any errors!