Is it possible to check for an attribute specifier in C ++?

I am trying to achieve different behavior based on an attribute being applied to a function. Basically I'm trying to check if it is possible to check for the existence of an attribute at compile time.

struct AbortError
{
    [[noreturn]] static void error(const std::string& msg)
    {
        std::cerr << "critical error: " << msg << std::endl;
        std::abort();
    }
}

struct LogError
{
    static void error(const std::string& msg)
    {
        std::cerr << "non-critical error: " << msg << std::endl;
    }
}

      

Can I check for [[noreturn]]?

I am hoping to get something like

template <typename ErrorPolicy>
void function()
{
    // ...
    if constexpr(std::is_noreturn<ErrorPolicy::error>::value)
    {
        performCriticalCleanup();
    }

    ErrorPolicy::error("Bad things happened.");
}

      

+3


source to share


1 answer


Since C ++ doesn't have reflection , the answer is no : it's not possible.

Instead, I suggest that you make a different design choice to achieve the same goal. You can use runtime polymorphism, for example.

If you need some compilation time, you can instead "integrate" the constant expression into your structure and test it later.

For example:



struct AbortError {
  static constexpr bool critical = true;
  // ...
};

      

or

struct AbortError: std::true_type {
// ...
};

      

Here's an online example that shows both options.

+1


source







All Articles