C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Tagging

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 20 Apr 2025 00:11:26 +0100
On Sat, Apr 19, 2025 at 11:58 PM Frederick Virchanza Gotham wrote:
>
> There is another method of tagging though that
> allows you to leave the class definition intact, as follows:
>
> template<typename T>
> constexpr bool tag_arithmetic = false;
>
> class MyClass {};
>
> template<>
> constexpr bool tag_arithmetic<MyClass> = true;
>
> class MyDerivedClass : public MyClass {};
>
> template<>
> constexpr bool tag_arithmetic<MyDerivedClass> = true;
>
> template<typename T>
> void Func(void)
> {
> static_assert( tag_arithmetic<T> );
> }
>
> int main(void)
> {
> Func<MyDerivedClass>();
> }
>
> As you can see in the above code snippet, the tag is not automatically
> inherited by derived classes.


Yet another way of doing tagging: Looking at the above code, the tag
can be made inherited by default as follows:

    #include <type_traits>

    template<typename T>
    constexpr bool tag_arithmetic = false;

    class MyClass {};

    template<typename T> requires std::is_base_of_v<MyClass, T>
    constexpr bool tag_arithmetic<T> = true;

    class MyDerivedClass : public MyClass {};

    template<typename T>
    void Func(void)
    {
        static_assert( tag_arithmetic<T> );
    }

    int main(void)
    {
        Func<MyDerivedClass>();
    }

And then the derived class can opt out as follows:

    #include <type_traits>

    template<typename T>
    constexpr bool tag_arithmetic = false;

    class MyClass {};

    template<typename T> requires std::is_base_of_v<MyClass, T>
    constexpr bool tag_arithmetic<T> = true;

    class MyDerivedClass : public MyClass {};

    template<>
    constexpr bool tag_arithmetic<MyDerivedClass> = false;

    template<typename T>
    void Func(void)
    {
        static_assert( tag_arithmetic<T> );
    }

    int main(void)
    {
        Func<MyDerivedClass>();
    }

Received on 2025-04-19 23:11:35