Silvan Hau
Silvan Hau

Reputation: 85

Template specialization with variadic template for a create method

I want to create a static method in a class which basically just creates components for me and i want to overload this method for different classes, but i just can't get it to work. This is the best i came up with so far:

    template <typename T, typename... Args>
    static T* _Create(Args&&... args) 
    {
        T* component = new T(std::forward<Args>(args)...);
        return component;
    }

    template <typename T, typename... Args, typename std::enable_if<std::is_same<Camera, T>::value>::type* = nullptr>
    static T* _Create(Args&&... args) 
    {
        T* component = new T(std::forward<Args>(args)...);
        // Do stuff with the component e.g. add it to a list
        return component;
    }

    template <typename T, typename... Args, typename std::enable_if<std::is_base_of<CRenderer, T>::value>::type* = nullptr>
    static T* _Create(Args&&... args) 
    {
        T* component = new T(std::forward<Args>(args)...);
        // Do stuff with the component e.g. add it to a list
        return component;
    }

But of course this doesn't work because the _Create with "Camera" does match the first and second function. Can somebody please push me in the right direction? How can i achieve this?

Upvotes: 0

Views: 80

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63725

Since you have access to C++17 (and have shown hesitance to add more enable_ifs)...

You may collapse all your functions into one using if constexpr!

template <typename T, typename... Args>
static T* _Create(Args&&... args) 
{
    T* component = new T(std::forward<Args>(args)...);

    if constexpr( std::is_same<Camera, T>::value )
    {
        // Do stuff with the component e.g. add it to a list
    }

    if constexpr( std::is_base_of<CRenderer, T>::value )
    {
        // Do stuff with the component e.g. add it to a list
    }

    return component;
}

This will produce code as efficient as the code you have written.

Upvotes: 2

Related Questions