Overloading templates

by (Login ComputerGhost)
R

Templates can be specialized but not overloaded.

I want to create a struct A that takes either a template, a type, or a constant as a template parameter.

One solution builds off of the fact that functions can be overloaded, and the idea is to use the functions to create the objects. This isn't perfect, but it gets us closer to the goal.

/*
* First, start with the objects
*/

template<template<typename...> class Template>
struct A_template
{
};

template<typename Type>
struct A_type
{
};

template<int Value>
struct A_value
{
};

/*
* Then we have the functions for creation
*/

template<template<typename...> class Template>
A_template<Template> CreateA()
{
return A_template<Template>();
}

template<typename Type>
A_type<Type> CreateA()
{
return A_type<Type>();
}

template<int Value>
A_value<Value> CreateA()
{
return A_value<Value>();
}

/*
* And to use this magic:
*/

int main()
{
auto test1 = CreateType<vector>();
auto test2 = CreateType<int>();
auto test3 = CreateType<42>();
return 0;
}


It works! CreateType<vector>(), CreateType<string>(), CreateType<map>(), CreateType<map()>(), and CreateType<double>() all work! Aye, but those that are templates have one thing in common: they are of the form template<typename, typename...> class ClassName; this doesn't work with C++0x's new array type, which is of the form template<typename, int> class array.

CreateType can accept a template as a template parameter only if that template takes typenames as parameters. The whole idea falls apart with "odd" templates such as the array.

At first thought, one would think that we can overload CreateType again to accept a template parameter that takes a typename and a constant. But there's the rub! Doing this would require us to overload the template, not the function, and templates can't be overloaded. We already have a TEMPLATEd CreateType function that takes a TEMPLATE, and we want to make another TEMPLATEd CreateType function that takes a TEMPLATE? Won't work. Compilers aren't that smart yet I suppose.

So, here's my question: How do I create the illusion of overloading templates in a way that has no problems like my above solution?





    
This message has been edited by ComputerGhost on Feb 21, 2012 1:21 PM
This message has been edited by ComputerGhost on Feb 21, 2012 1:19 PM

Posted on Feb 21, 2012, 1:19 PM

Respond to this message   

Return to Index


Response TitleAuthor and Date
* Example in C++0x for more compactness, but this can be done in TR1 too. on Feb 21
Create the illusion of overloading templates? Not really...ChronoKitsune on Feb 22
 * The only problem with my approach is the template parameters must be in syncChronoKitsune on Feb 22
 You are a genius. on Feb 22
  * I'm no genius. Just remember that arrays can't have sizes < 0. ;)ChronoKitsune on Feb 23