Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 having additional maintenance costs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading