Home > Enterprise >  Class template argument deduction using function return type
Class template argument deduction using function return type

Time:09-29

I want to make a class with a template parameter and a function (also with a template parameter) that returns a class instance.
However, for shorter code, I want to omit template parameters when returning the result of class construction.
I have no clue how do I call this type of technique and if it is possible.

For a better description of my question, the code below is an example that I am ideally seeking.

template <typename T>
class Class
{
public:
    Class()
    {
        // Construction  
    };
};

Class<int>
Function()
{
    return Class();
    // not Class<int>();
}

int main()
{
    Class<int> instance = Function();
}

Depending on how I apply this type of technique, I may also need to use multiple template parameters.

Thank you.

CodePudding user response:

This is not possible. Template types are concrete after compilation, unlike languages like C# where there's metadata so it can allow uncomplete generic types, C doesn't. Types like Class<> or Class<int,> are not possible.

You could do Class<void> and let template deduction fill the void (pun intended). Or you could template the function itself:

template <class TInner>
Class<TInner> Function()
{
    return Class<TInner>();
}

Best of luck.

CodePudding user response:

You do not have to name the return type in the return statement itself, the following works:

Class<int>
Function()
{
    return {}; // Calls Class<int>::Class() ctor.
}

But if you need to create an instance of that class inside the function, I would recommend returning auto:

auto Function()
{
    Class<int> instance;
    //Do something with instance...
    return instance;
}
  • Related