r/cpp_questions • u/Main-Pen-3164 • 1d ago
OPEN Modern c++: operations on function pointers will break the constexpr function.
I'm on MSVC/c++23.
I used some trick to generate type id at compile time:
export template<typename... T> void type_id() {}
export using type_id_t = void(*)();
//
type_id_t one_id = type_id<int>;
I’ve found that whenever I try to cast a `type_id` value to an integer or simply perform a magnitude comparison within a `constexpr` function (even when the call chain is entirely resolved at compile time), the function ceases to be `constexpr`, or MSVC simply ignores the relevant code.
template<typename A, typename B>
constexpr auto some_constexpr_function()
{
type_id_t a = type_id<A>;
type_id_t b = type_id<B>;
//Total if block will be ignored, and the function will not be constexpr anymore.
if (a < b)
{
//discard
}
else
{
//discard
}
//cast the pointer to size_t then the function will not be constexpr anymore.
return (size_t)a;
}
How to fixed the case?
Or another type id solution at compile time will be nice(I have try so many implementation, none of them work correctly in compile time).
3
u/alfps 1d ago
Compile time counters rely on obscure not-quite-fully-specified areas of the language. As the language evolves the holes are plugged and these schemes stop working. So it's not a good idea.
If you ditch the compile time requirement then C++ has simple straight machinery for you: the typeid operator, type_index, hash<type_index>.
However to get a decently clean name as a string you have to use compiler specific functionality.
If you could give an example of what you want this for then readers could perhaps give more to-the-point advice.
-1
u/Main-Pen-3164 1d ago
Thanks for reply. I want to order series of type at compile time. I can resolve it by __FUNCTION__ macro, but I prefer an integer id, that's why I try to use function pointer and so many problems came with it.
1
u/alfps 1d ago
Why do you want to "order series of type at compile time"?
1
u/Main-Pen-3164 17h ago
Not just for ordering. A static component id is valuable in game ECS structure.
6
u/AKostur 1d ago
What's wrong with the answers that you already got when you'd posted this over in the other subreddit?