Search code examples
c++templatestemplate-specializationclass-template

How to create a type trait to avoid writing redundant specializations?


I have a class template with a primary template that is meant to work with any type argument T. However, due to some particular needs, I need to use template specialization like this:

template<typename T>
class foo 
{
private:
    T result;
public:
    void modify_result(T a)
    {
        result = some_operations(a);
    }
};

template<>
class foo<uint64_t> 
{
private:
    uint64_t result;
public:
    // notice: uint32_t not the same as our template argument
    void modify_result(uint32_t a)
    {
        result = some_operations(a);
    }
};

The problem is that I have to create a large number of full specializations for each of my particular cases. If I ever want to modify or add something to the class, I will have to do it for every specialization, which is really bad for maintainability.

I would like to have some sort of type trait that checks the type of T. If T is of a certain type e.g. uint64_t, then we know that the input of the method or certain variables inside the method need to be of type uint32_t. This would enable me to customize my template without additional maintenance costs.


Solution

  • You can define a type trait, and add specialization for each particular type, like:

    template <typename T>
    struct parameter_type {
        using type = T;
    };
    
    template <>
    struct parameter_type<uint64_t> {
        using type = uint32_t;
    };
    

    Then use it as:

    template<typename T>
    class foo {
    private:
        T result;
    public:
        void modify_result(typename parameter_type<T>::type a) {
            result = some_operations(a);
        }
    };