I'm trying to write a conversion function.
I want to be able do something like this:

//ConversionType_1
    Convert<ConversionType_1>("Abc123");
    //ConversionType_2
    Convert<ConversionType_2>("Abc123");

I want to be able to switch between different data sets.

The solution I've come up with so far seems less than optimal to me:

enum ConversionType
{
    ConversionType_1,
    ConversionType_2
};

template <ConversionType>
struct Conversion
{
    static const int Data[];
    static const std::size_t dataSize;
};

template <>
const int Conversion<ConversionType_1>::Data[] = {0,...};

template <>
const std::size_t Conversion<ConversionType_1>::dataSize = 1;

template <ConversionType TConversionType>
void Convert(const std::string& s)
{
    if (Conversion<TConversionType>::Data[0])
    {}
    //...
}

Is there a better way?
I don't like having the enum really.
I thought about having base/derived classes to hold the data but then I have to redeclare the static variables in every derived class.

Your code is slightly ugly since you have two levels of derefrence and that can slow down understanding.

There are several methods that can be used. But what about using a policy class

class Conv1
{
   public:
     static const int data[];  
};

class Conv2 
{
 // same declaration but different data.
};

template <typename T>
void Convert(const std::string& s);
{
    if (T::Data[0]==54) {} //etc
}

int
main
{
    std::string A="fred";
    Convert<Conv1>(A);
    }

There are bits you are going to have to fill in but the idea is there (I hope). Obviously, it is possible to put a convert function INTO the classes Conv1/Conv2 etc, if the convert is significantly different.

You can do this by the basics functor approach but would want inherritance to get the same basic convert function but again that adds complexity for your example.

Thank you!

I remember the reason I had two levels of indirection was because it was sort of necessary.
I didn't want to have to declare the static variables in every single class I made.
There's actually about 6 data variables in each class.
So I figured I'd use templates to avoid the code duplication...and that made me introduce the enum.

I may go with your method though, I'm not sure.
I wish there was a better way.

This article has been dead for over six months. Start a new discussion instead.