Home > Net >  c : Avoid duplicate code during member function full specialization
c : Avoid duplicate code during member function full specialization

Time:08-15

Code: sorry for java style:

#include <iostream>
#include <map>

template<class K>
class Bundle {
    std::map<K, void *> mValueMap;

public:
    template<typename T>
    void put(K, const T& value) {
        std::cout << "put all, except std::string" << std::endl;
    };
};

template<>
template<>
void Bundle<const char*>::put<std::string>(const char* key, const std::string& value) { //duplicate code
    std::cout << "duplicate code:put std::string" << std::endl;
}

template<>
template<>
void Bundle<int>::put<std::string>(int key, const std::string& value) { //duplicate code
    std::cout << "duplicate code:put std::string" << std::endl;
}

int main() {
    Bundle<int> intBundle;
    Bundle<const char *> bundle;

    intBundle.put<float>(1, 45.0); // good
    bundle.put<float>("key", 45.0); // good

    intBundle.put<std::string>(1, std::string{}); // not good - duplicate code
    bundle.put<std::string>("key", std::string{}); // not good - duplicate code
}

I could only think of such working methods of specialization. Is it possible (using partial specialization or other methods) to get rid of code duplication.

CodePudding user response:

Instead of full specialization, you might use if constexpr (C 17):

template<class K>
class Bundle {
    std::map<K, void *> mValueMap;

public:
    template<typename T>
    void put(K, const T& value) {
        if constexpr((std::is_same_v<K, const char*> && std::is_same_v<T, std::string>)
            || (std::is_same_v<K, int> && std::is_same_v<T, std::string>)) {
            std::cout << "put std::string" << std::endl;
        } else {
            std::cout << "put all, except std::string" << std::endl;
        }
    }
};

CodePudding user response:

Whether its code in a specialization or elsewhere, the first measure to fight code duplication is functions:

void do_common_thing() {
    std::cout << "duplicate code:put std::string" << std::endl;
}

Then call this function in the specializations of your template.

CodePudding user response:

I could only think of such working methods of specialization. Is it possible (using partial specialization or other methods) to get rid of code duplication.

The simplest(staightforward) way that I can think of is by putting your duplicate code into a separate function and then call that function from inside the specializations.

Something like:

void dupeCode()
{
    //duplicate code put here
    std::cout << "duplicate code:put std::string" << std::endl;
}

Then you can call the above function from inside the specializations:

template<>
template<>
void Bundle<const char*>::put<std::string>(const char* key, const std::string& value) { 
    dupeCode();
}

template<>
template<>
void Bundle<int>::put<std::string>(int key, const std::string& value) { 
    dupeCode();
}
  • Related