jmasterx
jmasterx

Reputation: 54113

Avoiding code duplication with different data types?

I have some methods like this in my class:

static std::string numberToString(int n);
static std::string numberToString(float n);
static std::string numberToString(double n);
std::string encodeVector(const std::vector<int>& intVec);
std::string encodeVector(const std::vector<float>& floatVec);
std::string encodeVector(const std::vector<double>& doubleVec);

The encode method depends on the numberToString method.

Is there a way to make this more generic and avoid code duplication?

Thanks

Upvotes: 2

Views: 115

Answers (2)

Jason
Jason

Reputation: 32510

Sure, you could always make a template version of your function inside the class like so:

class myclass
{
    template<typename T>
    static typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type numberToString(T n);

    template<typename T>
    typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type encodeVector(const std::vector<T>& vec);
};

The use of std::enable_if is mainly there to prevent someone from passing a non-arithmetic type to your function. You could create another predicate other than std::is_arithmetic to block or include other types.

Upvotes: 0

Chad
Chad

Reputation: 19032

Sure. (Caveat: have not compiled)

#include <sstream>
#include <vector>

// All types used in the to_string() function have to 
// have an appropriate operator << defined.
template <class T>
std::string to_string(const T& v)
{
    std::stringstream out;
    out << v;
    return out.str();
}

// generic for vector of any type T
template <class T>
std::string encodeVector(const std::vector<T>& vec)
{
    std::string r;

    for(size_t x = 0; x < vec.size(); ++x)
       r += to_string(vec[x]);

    return r;
}

Upvotes: 3

Related Questions