Click here to Skip to main content
15,886,625 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I've written a series of templates to fill in a 32 character string based on up to 32 data types. Is it possible to compute this at compile time?

My assumption is no, but wanted to verify in case I was wrong.

Example of code to generate registration string with 3 data types
XML
temp[0]=Char_Type<T1>();
temp[1]=Char_Type<T2>();
temp[2]=Char_Type<T3>();
return temp;
Posted

Maybe this would be some food for thought
C++
template<typename T> inline char char_type()       { return '-'; }
template<>           inline char char_type<char>() { return 'c'; }
template<>           inline char char_type<int>()  { return 'd'; }

template <typename T1, typename T2>
class MyClass
{
public:
    static char temp[]; // Will be init'ed at compile time
};

template <typename T1, typename T2>
char MyClass<T1, T2>::temp[] = { char_type<T1>(), char_type<T2>(), 0 };

int main()
{
    cout << MyClass<int, char>::temp << endl;
    cin.get();
    return 0;
}


Edit: Turned it into a working sample, and removed the constraints on the template parameters.
 
Share this answer
 
v6
Comments
T2102 8-Feb-11 20:10pm    
Thanks, I like your suggestion.
I'm not entirely sure what you're trying to achieve, but since each Char_Type<T> is a unique type, they can only be assigned to the same collection (in your case the temp[] array), if they're subclasses of the same base class (or an instance of that base class).

C++
class some_base
{
};
template<class T> class Char_Type : public some_base
{
public:
    T value;
    Char_Type()
    {
    };
    Char_Type(const T& v)
    {
        value = v;
    };
};
int main(int argc, char* argv[])
{
    some_base* a = new some_base[3];
    a[0] = Char_Type<char>('c');
    a[1] = Char_Type<int>(123);
    a[2] = Char_Type<int>(123.23);
    delete[] a;
    return 0;
}



But I think such a setup would cancel what you're trying to do.
 
Share this answer
 
Comments
T2102 8-Feb-11 7:47am    
I am wondering if I can compute a one-to-one mapping from a series of types to characters using metaprogramming.

I currently have a template with a list of types such as T1, T2, ..., T15.
My code fills a character array with I-th position filled based on the I-th type.
I am wondering if I can compute the character array at compile time somehow.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900