Search code examples
c++staticfunction-pointers

how to use a pointer to member function inside a static member function in c++


I'm actually trying to use a pointer inside a static function which is in the same class as the functions that i'm trying to use inside the pointer. I'm actually asked to use the class like this :

class Factory {
    public:
        Factory() = default;
        ~Factory() = default;
        static IOperand* createOperand(eOperandType type, const std::string& value);
    private:
        IOperand* createInt8(const std::string& value);
        IOperand* createInt16(const std::string& value);
        IOperand* createInt32(const std::string& value);
        IOperand* createFloat(const std::string& value);
        IOperand* createDouble(const std::string& value);
        IOperand* createBigDecimal(const std::string& value);
};

This is how I would do if this function wasn't static :

IOperand* Factory::createOperand(eOperandType type, const std::string& value)
{
    IOperand* (Factory::*ptr[6])(const std::string&) = {
            &Factory::createInt8,
            &Factory::createInt16,
            &Factory::createInt32,
            &Factory::createFloat,
            &Factory::createDouble,
            &Factory::createBigDecimal
    };
    return (*this.*ptr[type])(value);
}

ps: eOperandType is just an enum


Solution

  • No matter where you use the member function pointer to call a method, you need an object to do so. In your "This is how I would do if this function wasn't static" version you call the method on the current object this. In the static method, you need a different object of type Factory, because there is no this in the static method. I suspect that actually all methods of Factory should be static, though not touching that, you can do this:

    struct IOperand {};
    class Factory {
        public:
            Factory() = default;
            ~Factory() = default;
            static IOperand* createOperand(size_t type, const std::string& value) {
                Factory f;
                IOperand* (Factory::*ptr[6])(const std::string&) = {
                    &Factory::createInt8,
                    &Factory::createInt16,
                    &Factory::createInt32,
                    &Factory::createFloat,
                    &Factory::createDouble,
                    &Factory::createBigDecimal
                };
                return (f.*ptr[type])(value);
            }
        private:
            IOperand* createInt8(const std::string& value);
            IOperand* createInt16(const std::string& value);
            IOperand* createInt32(const std::string& value);
            IOperand* createFloat(const std::string& value);
            IOperand* createDouble(const std::string& value);
            IOperand* createBigDecimal(const std::string& value);
    };