C++ Logo

std-proposals

Advanced search

Re: [std-proposals] static static variable inside template function

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 3 Oct 2023 19:35:47 +0100
On Tue, Oct 3, 2023 at 6:37 PM Justin Cooke <jgc_at_[hidden]> wrote:
>
> It is unclear what you would want 'static static' to do in more complex cases.
> For example, should 'static static' within a member function template of a class
> template mean that the variable is shared across all combinations of instantiations
> of the class template and of the function template, or merely that it is shared across
> instantiations of the function template within each given instantiation of the enclosing
> class template ?


The following code:

    template<typename T>
    class Monkey {
        template<typename R>
        T *MemFunc(unsigned const arg)
        {
            static static std::string str(arg,'a');
            /* other stuff */
            return nullptr;
        }
    };

would behave as though it were written:

    std::optional<std::string> opt_str;
    std::once_flag myflag;

    template<typename T>
    class Monkey {
        template<typename R>
        T *MemFunc(unsigned const arg)
        {
            std::call_once( [arg](){ opt_str.emplace(5, 'a'); } );
            std::string &str = opt_str.value();
            /* other stuff */
            return nullptr;
        }
    };

Received on 2023-10-03 18:35:59