문제

I have a function that I want to be able to runtime check the argument types of as I'm casting a void pointer back to a function. Curious as to how I turn the list of arguments into into a hash using the TypeToEnum template that is constructed like

    #define DEFINE_TYPE(x)\
    template<>\
    struct TypeToEnum<x>\
    {\
      public:\
      static const unsigned int value = HashString(#x);\
    };\

That way I can determine the function signature using templates. I just have no idea how to convert that into a static const array in the invoke method.

    class FunctionDescription
    {
    private:
      int return_type;
      std::vector<int> argument_types;
      std::string m_name;
      void* function;
    public:
const std::string& name() const{ return m_name; }

int ReturnType() const { return return_type; }

const std::vector<int>& arguments() const { return argument_types; }

template<typename Return,typename... Args>
FunctionDescription(const std::string& _name, Return(*func)(Args...)) 
    : m_name(_name), return_type(TypeToEnum<Return>::value)
{
    argument_types = { TypeToEnum<Args>::value... };
    function = func;
}

template<typename Return,typename... Args>
Return invoke(Args... args)
{
    static const int type_check[] = {TypeToEnum<Return>::value,TypeToEnum<std::forward<Args>>::value};

    if (type_check[0] != return_type)
        throw std::exception("Invalid return type for given call");

    for (int i = 1; i < sizeof...(Args) + 1; i++)
    {
        if (type_check[i] != argument_types[i])
            throw std::exception("Invalid argument type for the given call");
    }

    return Return(*func)(Args...)(args...);
}
};
도움이 되었습니까?

해결책

TypeToEnum<std::forward<Args>>::value to TypeToEnum<Args>::value..., but I'd instead do

template<typename Return,typename... Args>
Return invoke(Args...&& args){
  static const int type_check[] = {
    TypeToEnum<Return>::value,TypeToEnum<typename std::decay<Args>::type>::value...
  };

  if (type_check[0] != return_type)
    throw std::exception("Invalid return type for given call");

  for (int i = 1; i <= sizeof...(Args); i++)
  {
    if (type_check[i] != argument_types[i])
      throw std::exception("Invalid argument type for the given call");
  }

  typedef Return(*func_t)(typename std::decay<Args>::type...);
  return static_cast<func_t>(function)( std::forward<Args>(args) );
}

as a first pass. I would then replace decay with a custom type mapping that handles std::reference_wrapper properly, so callers can say "I expect this argument to be a ref" by saying invoke( std::ref(x) ).

Next, I would consider using the typeid instead of all of your machinery. Your hash isn't perfectly reliable, among other problems.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top