Search code examples
c++templatesctad

Class template argument deduction using function return type


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.


Solution

  • 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.