0

This question is partly common to C++ Get name of type in template . I am trying to come up with a template/macro that expand to static_assert(std::is_trivially_destructible<T>::value, #T" is not trivally destructible"); so that I can use a shorthand in my code. But looks like there is no compile time way of knowing the name of T in a template.

The other approach of using a macro is also not good since it will move the errors to incorrect line numbers (i.e. within the macro). See example of errors with a macro as below:

macro.cpp:5:17: error: static assertion failed: std::vector<int> should be trivial 
static_assert(std::is_trivially_destructible<T>::value, #T" should be trivial"); 
^~~ 
macro.cpp:10:3: note: in expansion of macro ‘STATIC_ASSERT_TRIVIALLY_DESTRUCTIBLE’ 
STATIC_ASSERT_TRIVIALLY_DESTRUCTIBLE(std::vector<int>); 
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cigien
  • 57,834
  • 11
  • 73
  • 112
sanjivgupta
  • 396
  • 3
  • 12
  • This would really need to be forwarded by a macro, but from the caller's site unfortunately. I've got low hopes to get this working in a reasonable way. Would be interested to see an answer. – πάντα ῥεῖ Jan 06 '21 at 21:41
  • Regarding the macro: most compilers will additionally report the line on which the macro was used. – HolyBlackCat Jan 06 '21 at 21:45
  • Are you constrained to C++14? There may be a way to do this with `std::source_location` from C++20 though I'm not sure about that at all. – cigien Jan 06 '21 at 21:50
  • @cigien yes, unfortunately can't go past c++14 as of now. – sanjivgupta Jan 06 '21 at 23:13
  • 3
    Please add all that relevant information to the question, not as a comment. – cigien Jan 06 '21 at 23:24
  • Thanks for adding the error messages. You don't need to mention that you're restricted to C++14, that's implied by the tag. My comment was simply asking for a confirmation about that. – cigien Jan 06 '21 at 23:46
  • Hmm. The title seems to suggest that you're looking for a more concise way of doing `static_assert`, but the body of your questions seems that you're more interested in finding a way to output the value of `T` correctly. I'd search for "compile time printing". [Here's an example](https://github.com/saarraz/static-print) of someone who's managed something similar to what you want. – Elliott Jan 07 '21 at 01:06

0 Answers0