3

Can I detect via templates, concepts or in any other constexpr way if a function is being run in a static context? Something like this:

template <typename T = SomeTypeIfImStatic_SomeOtherTypeIfImNot>
class FBlah
{
    void foo()
    {
        if constexpr (AmIStatic) { ... } else { ... }
    }
};

Alternatively, like this:

template <typename T = SomeTypeIfImStatic_SomeOtherTypeIfImNot>
class FBlah
{
};

Would like to differentiate between being run in a static FBlah Blah; or an FBlah Blah; inside of an FBlah itself.

I'm aware that I could declare two types, one for static FBlah the other for non-static but I'm looking for a compile-time way to do this. I'm using C++20.

GlassBeaver
  • 196
  • 4
  • 15
  • 1
    Pretty sure there isn't anything for this. If we were able to query the storage duration of objects it would definitely allow a lot less bugs to be created. – NathanOliver Apr 20 '22 at 19:18
  • 1
    I think it would cause more bugs than it would prevent... – Brian Bi Apr 20 '22 at 19:24
  • 6
    Maybe your are looking for [`std::is_constant_evaluated`](https://en.cppreference.com/w/cpp/types/is_constant_evaluated)? Also, as a note, C++23 will have [`if consteval`](https://en.cppreference.com/w/cpp/language/if#Consteval_if). Also compare [this post](https://stackoverflow.com/a/68213013/3740047). – Sedenion Apr 20 '22 at 19:32
  • Do you mean `static` as only this translation unit/cpp file or `static` as class variable or `static` variables inside functions, which are initialized once and keep their value? Your example `static FBlah Blah;` could be all three. – Sebastian Apr 20 '22 at 20:15
  • @Sebastian I was thinking any kind of `static` i.e. the static storage specifier in general but I'm open to suggestions for any and all kinds of statics. – GlassBeaver Apr 20 '22 at 20:19
  • 1
    At runtime you could perhaps detect in `Blah`, whether `this` points to the stack. At compile-time it is more difficult. Preprocessor macros replacing `static` perhaps? Otherwise reflection in C++29? Or can you write the static variable declaration in a way that the constructor is const evaluated for static storage duration? – Sebastian Apr 20 '22 at 20:26
  • 2
    The function doesn't know at compile time where it's going to be called from, so I'd say what you're asking for is impossible. – Mark Ransom Apr 20 '22 at 20:40

0 Answers0