It is possible to write, but the compiler dont find the function when I want to use func(x):

template <class T>
double func(const double& x, const double& error = 0)
{...}

I have to write separately, like this why?

template <class T>
double func(const double& x, const double& error)
{...}

template <class T>
double func(const double& x)
{double error = 0; ...}

Dani AI

Generated

Short version: the compiler can't deduce a template parameter that never appears in the function's parameter list. That is why sees the templated overload not considered. was right to point out the language rule, and 's question about whether T is used hints at the real cause.

When calling a function template, the compiler attempts to deduce template arguments from the call site. If the template parameter does not participate in deduction (it is not present in parameter types or deducible return context), the compiler has no value to infer and the template won't be selected unless an explicit template argument is provided. See the rules on template argument deduction: template argument deduction.

Practical fixes:

  • Drop the template if the function is for double only and use a normal function with a default parameter.
  • Make the template parameter participate in deduction (use T in a parameter type) so the call can infer it.
  • Provide the template argument explicitly at the call site, e.g. func<double>(x);.
  • Give the template a default template argument so deduction is unnecessary, for example:
template<typename T = double>
double func(double x, double error = 0.0) { /* ... */ }
  • If the intent is an optional error value, prefer std::optional<double> in modern C++ rather than sentinel values or raw pointers; 's pointer idea works, but requires null checks and is less expressive than std::optional (std::optional).

In short: either make T deducible, supply it explicitly, use a default template parameter, or stop using a template if it serves no purpose.

Recommended Answers

All 5 Replies

Because that's not how C++ was defined.

It is possible to write, but the compiler dont find the function when I want to use func(x):

template <class T>
double func(const double& x, const double& error = 0)
{...}

Reference to ... what? NULL?

Are you passing by reference when you don't need to? Are you using T anywhere?

template <class T>
double func(const T &x, double error = 0)
{
   // ...
   return x;
}

int main(){
   double a = 1.0 / 3.0, err = 5;
   func(a,err);
}

??

but you cannaot call func(a), can you?

Instead of const double& error = 0 you could code it as const double* error = NULL . References can not be NULL, but pointers can.

but you cannaot call func(a), can you?

Simply giving it a try would have gotten you an answer much quicker.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.