Search code examples
c++templatesgenerics

Template for similar members of different classes


Is there a way to implement a template for similar members of different classes?

In the code below two classes differ only by type of the map used in them while all the code in parse is similar.

Can I somehow define a template for parse function to avoid code duplication here?

#include <string_view>
#include <unordered_map>
#include <concurrent_unordered_map.h>

class SingleThreadedParser {
    std::unordered_map<std::string_view, int> dict;
public:
    std::vector<int> parse(std::string_view) {
        std::vector<int> res;
        ///  a lot of code woking with dict 
        return res;
    }
};

class MultithreadedParser {
    Concurrency::concurrent_unordered_map<std::string_view, int> dict;
public:
    std::vector<int> parse(std::string_view) {
        std::vector<int> res;
        ///  a lot of code woking with dict
        return res;
    }
};

int main()
{
    std::string some_string = "Test";

    SingleThreadedParser sp;
    MultithreadedParser mp;

    auto sp_res = sp.parse(some_string);
    auto mp_res = mp.parse(some_string);
}

The performance is critical so I want to avoid wrapping the maps and using dynamic polymorphism to access them. That's why I am interested in template-based implementation.

Is that possible?


Solution

  • This might be what you want.

    template<template<typename Key, typename Value> typename MapType>
    class Parser
    {
        MapType<std::string_view, int> dict;
    public:
        std::vector<int> parse(std::string_view) {
            std::vector<int> res;
            ///  a lot of code woking with dict 
            return res;
        }
    };
    
    using SingleThreadedParser = Parser<std::unordered_map>;
    using MultithreadedParser = Parser<Concurrency::concurrent_unordered_map>;