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.
Whether its code in a specialization or elsewhere, the first measure to fight code duplication is functions:
Then call this function in the specializations of your template.