fork download
  1. #include <new>
  2. #include <utility>
  3. #include <type_traits>
  4.  
  5. struct A
  6. {
  7.  
  8. };
  9.  
  10. struct B
  11. {
  12. int i;
  13. };
  14.  
  15. template<typename T, typename U, typename... Args>
  16. T* construct(U ptr, Args&&... args)
  17. {
  18. static_assert(std::is_same<U, void*>::value or std::is_same<U, char*>::value, "must be void* or char*");
  19. return ::new(ptr) T(std::forward<Args>(args)...);
  20. }
  21.  
  22. int main()
  23. {
  24. A a;
  25. alignas(B) char area[sizeof(B)];
  26. void* ptr = area;
  27. construct<B>(&a); // fails at compile time
  28. construct<B>(&area[0]);
  29. construct<B>(ptr);
  30. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In instantiation of 'T* construct(U, Args&& ...) [with T = B; U = A*; Args = {}]':
prog.cpp:27:17:   required from here
prog.cpp:18:2: error: static assertion failed: must be void* or char*
  static_assert(std::is_same<U, void*>::value or std::is_same<U, char*>::value, "must be void* or char*");
  ^
stdout
Standard output is empty