Formulation of a static member of a template template

I am trying to create a program that executes some code only if the template instance (it will be used to initialize the low level driver). Now I have the following solution.

class Initializer
{
public:
    Initializer(){
        // This code is executed once
    }

    void silly() const{

    }
};

template <class T>
class Proxy{
protected:
    static const Initializer init;
};

template<class T>
const Initializer Proxy<T>::init;

template<class T>
class MyTemplate : public Proxy<void>{
public:
    static void myMethod1(){
        init.silly();

        // ... Something useful
    }

    static void myMethod2(){
        init.silly();

        // ... Something useful
    }
};

The default constructor Initializeris only executed if I call myMethod1()or myMethod2()somewhere.

But is there a way to get rid of these init.silly();lines?

+6
source share
2 answers

Your problem is that template members are not created if they are not referenced.

Instead of calling, init.silly()you can just reference the element:

    static void myMethod1(){
        (void)init;

        // ... Something useful
    }

, , init , :

template<>
const Initializer Proxy<void>::init{};
+2

?.. C .

- :

class Initializer
{
public:
    Initializer() {
        // This code is executed once
    }
};

template <class T>
class Proxy {
protected:
    Proxy()
    {
        static Initializer init;
    }
};

template<class T>
class MyTemplate : public Proxy<void> {
public:
    void myMethod1() {
        // ... Something useful
    }

    void myMethod2() {
        // ... Something useful
    }
};

, . myMethod1 myMethod2 , Proxy() Initializer .

, - Initializer , . ? , , . :

class Initializer
{
    Initializer() {
        // This code is executed once
    }
public:
    void init()
    {
        static Initializer init;
    }
};


template<class T>
class MyTemplate {
public:
    static void myMethod1() {
        Initializer::init();
        // ... Something useful
    }

    static void myMethod2() {
        Initializer::init();
        // ... Something useful
    }
};

, Initializer , myMethod1 myMethod2. Initializer::init, Initializer .

+2

Source: https://habr.com/ru/post/1676447/


All Articles