Get variable type to pass to template

Apr 24, 2016 at 3:10pm
I have this situation:
1
2
3
4
template <typename T>
T* func(); // Does things

MyClass* c = new MyDerivedClass();

My question is: How can I pass to func<>() 'MyDerivedClass' as template parameter (note: in this case it's 'MyDerivedClass' but it could be any derived class, so the method needs to be dynamic)?
Last edited on Apr 24, 2016 at 3:10pm
Apr 24, 2016 at 3:41pm
There no way you can pass the dynamic type of *c as a template argument. Template arguments has to be known at compile-time.
Apr 24, 2016 at 3:49pm
@Peter87 Any workaround with macros?
Apr 24, 2016 at 3:51pm
Have you considered using function overriding?
Apr 24, 2016 at 3:53pm
@Peter87 Like?
Apr 24, 2016 at 3:58pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <typename T>
T* func(); // Does things

class MyClass
{
public:
	virtual MyClass* func() { return ::func<MyClass>(); }
};

class MyDerivedClass : public MyClass
{
public:
	virtual MyDerivedClass* func() { return ::func<MyDerivedClass>(); }
};

int main()
{
	MyClass* c = new MyDerivedClass();
	c->func();
}
Apr 24, 2016 at 4:03pm
Well, I should do that for every derived, class... I was looking for something dynamic.
I have this class method and I have to call it from a derived class, not an external one... I have just to pass its class back to the parent method to call it...
Apr 24, 2016 at 5:26pm
If for template < typename T > T* func() ; type T must be a class derived from base
and it would be acceptable to change the result type of the function to base*
ie. template < typename T > base* func() ;

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
#include <iostream>
#include <type_traits>
#include <typeinfo>

struct base ; template < typename T > base* func() ;

struct base  { virtual base* invoke_func() const { return func<base>() ; } /* ... */  };

template < typename T > struct invoke_helper : base
{ virtual base* invoke_func() const override { return func<T>() ; } };

template < typename T > base* func()
{
    static_assert( std::is_base_of<base,T>::value, "T must be a type derived from 'base'" ) ;
    std::cout << "func< " << typeid(T).name() << " >()\n" ;
    return nullptr ; // placeholder
}

struct derived_one : invoke_helper<derived_one> {};
struct derived_two : invoke_helper<derived_two> {};
struct derived_three : invoke_helper<derived_three> {};

int main()
{
    derived_one d1 ;
    derived_two d2 ;
    derived_three d3 ;

    base* pointers[] = { std::addressof(d1), std::addressof(d2), std::addressof(d3) } ;
    for( base* p : pointers ) p->invoke_func() ;
}

http://coliru.stacked-crooked.com/a/5bdccca83f21f72f
http://rextester.com/UDCIJN90085
Topic archived. No new replies allowed.