Const / non const template method

Suppose we have code like this:

template<class CALLBACK>
struct INIFile{
    INIFile(CALLBACK &processor) :
                    processor(processor     ){}

    bool process(){
        // lots of code here,
        // call processor
        processor(123);

        return true;
    }

    CALLBACK    &processor;
};


struct MyProcessor{
    void operator()(int val){
        // do something
    }
};

struct MyConstProcessor{
    void operator()(int val) const{ // !!!!!
        // do something
    }
};

int main(){
    MyProcessor p;
    INIFile<MyProcessor> ini(p);
    ini.process();

    // const case:
    MyConstProcessor cp;
    INIFile<MyConstProcessor> cini(cp);
    cini.process();
}

In both cases, it is INIFile<>::process()not a member function const.

Is there an easy way to make a member function process()a constif CALLBACK::operator()is constwithout duplicating all the logic in INIFile<>::process()?

+4
source share
2 answers

Your problem has been resolved by following these steps:

template<class CALLBACK>
struct INIFile{
    INIFile(CALLBACK &processor) :
                    processor(processor){}

    template <class T>
    bool process_impl(T& processor) const {
        // deliberately shadow processor
        // reduce likelihood of using member processor, but can use other member variables

        // lots of code
        processor(123);
        return true;
    }

    bool process() const {
        return process_impl(const_cast<const CALLBACK&>(processor));
    }
    bool process() {
        return process_impl(processor);
    }

    CALLBACK&    processor;
};

, , process, , . processor const, process const const- , ( ). , const process , const , , , , .

, const, . , process const- INIFile, process const.

, , , . , , , process_impl - processor, - , .. , (, ). . , , .

+3

, , .

.

, nullptr.

template<class CALLBACK>
struct INIFile{
    INIFile(CALLBACK &processor) :
                    processor(& processor ){}

    bool process() const{
        // lots of code here,
        // call processor
        processor->operator()(123);

        return true;
    }

    CALLBACK    *processor;
};
0

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


All Articles