Tomasz
Tomasz

Reputation: 343

Can typeid be used to invoke a templated c++ function

Can typeid (or some other way to dynamically pass the type) be used to invoke a templated function.

Ultimately I need a conversion function which will convert data buffers from about a dozen source types to a dozen destination types which leads to hundred cases to statically code. It would be nice to be able to pass type information for source and destination which would automatically build the appropriate template function and invoke it.

Here is the simplified code that demonstrates what I am trying to do:

template<typename T>
void myFunc(T buf, int val) { *buf = val; }

const std::type_info& GetTypeInfo(int csType)
{
  switch(csType)
  {
    case dsCHAR:
    {
      return typeid(char*);
    }
    case dsWCHAR:
    {
      return typeid(wchar_t*);
    }
    default:
    {
      return typeid(int*);
    }
  }
}

void convert(void* buf, int csType, char* src, int len)
{
  const std::type_info& theType = GetTypeInfo(csType);
  for(int ix = 1; ix < len; ix++)
  {
    myFunc<theType>(&dynamic_cast<theType>(buf)[ix], src[ix]); // <- This fails to compile
  }
}

Using type_info& with the template or in a cast is not allowed by the compiler and I have not been able to figure out how to get around it, if it is even possible.

Upvotes: 0

Views: 191

Answers (1)

Another HM
Another HM

Reputation: 148

At the first you are using dynamic_cast ... and it's in the runtime, and the next instruction is a function that is template<typename T> ... that is in compile time!

so it's not possible , you should decide do you want to do that in runtime or compile-time.

I think you need something like this(GodLambda :D)


enum CHARS { dsCHAR, dsWCHAR };
using csType = CHARS;
using MyFunc = std::function<bool(void*)>;
std::map<csType, MyFunc> godLambda = {
    {dsCHAR,
     [](void* ptr) -> bool {
       auto theType = reinterpret_cast<char*>(ptr);
       if (nullptr == theType) return false;
       // my func specialize:
       return true;
     }},
    {dsWCHAR,
     [](void* ptr) -> bool {
       auto theType = reinterpret_cast<wchar_t*>(ptr);
       if (nullptr == theType) return false;
       // my func specialize:
       return true;
     }}
};

Upvotes: 2

Related Questions