Take template parameter from User

Hi,

I have a class whose template parameter I want to take from the user. Problem is these template parameters are user defined data types.

This is what I was trying to do but I am stuck now. Can someone help me on this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A{};

class B{};

template<typename T>class my_class{};

??? getTemplate(int id){
  switch(id){
    case 0:
      return A;
    case 1:
      return B;
  }
  return 0;
}

void main(){
  int a;
  cin>>a;

  my_class<getTemplate(a)> my_object; 
}


Thanks.
All template stuff is done at compile time.

as far as I know it is impossible to create new types at runtime
I am not sure what exactly you're trying to do but maybe template specialization might help.
http://www.cprogramming.com/tutorial/template_specialization.html
is there any relation between class A and class B
> Problem is these template parameters are user defined data types.

You would need each class A, B, to have a unique id, and users who define these data types would have to specialize a metafunction which maps the id to the type.
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Metafunction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
template< typename T > class my_class {};

template< int N > struct get_type ; // generalization is not defined

struct A { enum { id = 0 }; } ;
template <> struct get_type<0> { typedef A type ; };

struct B { enum { id = 1 }; } ;
template <> struct get_type<1> { typedef B type ; };

// etc ..

int main()
{
    int a ;
    std::cin >> a ;
    switch(a)
    {
        case 0:
        {
            my_class< typename get_type<0>::type > my_object ;
            // use my_object
        }
        case 1:
        {
            my_class< typename get_type<1>::type > my_object ;
            // use my_object
        }

        // etc ...

        default:
        {
            // error; no type matches this id
        }
    }
}


Perhaps you could provide a couple of macros which would automate the process. For something more elaborate, the Boost.MPL library would be handy.
http://www.boost.org/doc/libs/1_48_0/libs/mpl/doc/index.html


Oh! Irrespective of what username you fancy,
Even if your compiler accepts "void main()" avoid it, or risk being considered ignorant by C and C++ programmers.
- Stroustrup in http://www2.research.att.com/~bs/bs_faq2.html#void-main



Last edited on
1
2
template<typename T>class my_class : public super{};
super* getTemplate(int id);
Topic archived. No new replies allowed.