Variadic templates, safe to take address of rvalue or trick the compiler?

I have a question on dealing with rvalues, say I have this class,
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
32

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, my real class is more complicated than this, but this illustrates the point. In general, it seems like the compiler doesn't know that if you get to the assignment operation in foo::set that the two types are the same, so it complains. Using a type cast doesn't work generally because the casts between certain types are not defined, and again, the compiler isn't smart enough to know that at that statement, the types are the same. I can use the above method to trick the compiler, and it seems safe to me since I know that the types are exactly the same. But, is this safe? And is there a better way to deal with this? Thanks
Last edited on
This seems okay to me since the assignment will only execute if the types are the same, right? But in that case, why not just say
1
2
3
4
void set(T&& val)
  {
        bar = val;
  }

After all, the code will only work with this version of the set() function.
The actual class is much more complicated. It uses a variadic template and it seems like the compiler wants the assignment operation to be valid for each type in the parameter pack.

Edit: I modified the original post to give a more informative description of the class.
Last edited on
Topic archived. No new replies allowed.