Home > Back-end >  Calling template function inside another one but for function returning template type
Calling template function inside another one but for function returning template type

Time:08-05

I cannot understand why I can't build this code:

template<typename T> T* func ( void )
{
    return NULL;
}

template<typename T> T* func2 ( void )
{
    T* var = func();
    return NULL;
}

Compilation result is: "error: no matching function for call to ‘func()’" The code below is fine:

template<typename T> void func ( T var )
{
    return;
}

template<typename T> void func2 ( T var )
{
    func( var );
}

CodePudding user response:

The compiler needs to be able to determine the template parameter by some means. The type occurs in the function parameter list, the compiler often can deduce the type parameter based on the parameter passed. In the second example this is possible, since you pass var to func in func2.

If the functions do not take any function parameters, there's no way for the compiler to tell which template parameter to use without you explicitly specifying it, e.g.

template<typename T> T* func()
{
    return nullptr;
}

template<typename T> T* func2()
{
    T* var = func<T>();
    return nullptr;
}

CodePudding user response:

Templates aren't like generics in Java. Templates create multiple different versions of functions

template<typename T> T* func ( void )
{
    return NULL;
}

This is not a declaration of one function. It's a declaration of an infinite class of functions. When you write func(), C has no idea which one to call. In this particular case, it doesn't matter since they all return NULL, but in general it absolutely does. In your parameterized version, you take a parameter of type T, so when you call it, C is smart enough to see that the T must match the parameter's type, and it knows which one to call. That is, it converts func(var) to func<T>(var) for you.

If you want to call your 0-ary version, you need to give it an explicit type argument.

// Valid
func<int>();
func<double>();
func<T>(); // Assuming T is a template parameter in-scope
// Invalid (ambiguous)
func();
  •  Tags:  
  • c
  • Related