vendredi 15 mai 2015

Obtaining address of rvalue safety? Or suggestiong for better method

I have a question on how to deal with an issue I am having. I have a class similar to the following,

template<typename T, typename... Args>
class foo
{
public:
  template<typename U>
  void set(U&& val)
  {
    if( type_index(typeid(U)) == getTypeIndex() )
    {
      //trick the compiler!
      bar = *(T*)(void*)&val;
      return;
    }

    next().set<U>(val);
  }

private:
  type_index getTypeIndex()
  {
     return type_index(typeid(bar));
  }

  foo<Args...>& next()
  {
     return next_;
  }

  T bar;
  foo<Args...> next_;
}

So, the compiler complains at the assignment in foo::set unless I cast the type U into type T. However, it seems that the compiler does not know that the assignment can only occur when U and T are of the same type. So, it checks the assignment for every type contained in Args... Using a cast doesn't seem to work as casts between certain types (std::string to int) do not exist. First question would be, is the (T)(void*)&val cast safe? I think it should be as I have verified U == T is true so I am essentially casting val to itseld, but just want to see if there is anything I am missing. Second, is there a better solution to this?! Thanks

Aucun commentaire:

Enregistrer un commentaire