October 25, 2024
Chicago 12, Melborne City, USA
templates

Template deduction for function based on its return type?


I have a class (non-template) that specifies a template method whose parameter is only used in the return type (the code is only an example that should explain my problem):

class MyClass
{
  std::map<long, void*> elements;

  template <class T>
  T* getElement(long id)
  {
    if (elements.count(id) == 0)
      return (NULL);
    else
      return (dynamic_cast<T*>(elements.at(id)));
  }
};

When I try to do something like this:

MyClass x;
int*    value;
value = x.getElement(45);

The compiler complains that it cannot deduce template parameter 'T'.

Of course I could solve it by calling:

value = x.getElement<int>(45);

However, I’m quite sure it can be solved without specifying the type within the call.

This question is very similar but regards a function and not a class method.
How should I use the (accepted) answer of this question in a class template-method?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video