如何在此上下文中使用CRTP删除虚拟方法?

时间:2016-12-09 15:10:55

标签: c++ templates crtp

我有以下类似于我的代码库的程序。一个FunctionState类,它执行某种算法(可能在多个线程中),一个Function类控制FunctionState类的使用方式,并可能进行一些算法设置/拆卸操作。

#include <iostream>
#include <vector>

class FunctionState;

class Function {
public:
    virtual FunctionState* NewFunctionState() = 0;

protected:
    std::vector<FunctionState*> states;
};

class FunctionState {
public:
    FunctionState(Function* func) : mFunc(func) {}

    virtual void RunState() = 0;
    void ExecuteFunctionLotsAndLotsOfTimes();

private:
    Function* mFunc;
};

#define VERY_BIG_NUMBER 10

void FunctionState::ExecuteFunctionLotsAndLotsOfTimes() {
    for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
        RunState();
    }
};

class PrintFunction : public Function {
    FunctionState* NewFunctionState();
};

class PrintFunctionState : public FunctionState {
public:
    PrintFunctionState(PrintFunction* func) : FunctionState(func) {}

    void RunState() override {
        std::cout << "in print function state" << '\n';
    }
};

FunctionState* PrintFunction::NewFunctionState() {
    FunctionState* state = new PrintFunctionState(this);
    states.push_back(state);
    return state;
}

class AddFunction : public Function {
    FunctionState* NewFunctionState();
};

class AddFunctionState : public FunctionState {
public:
    AddFunctionState(AddFunction* func) : FunctionState(func), x(0) {}

    void RunState() override {
        ++x;
    }
private:
    int x;
};

FunctionState* AddFunction::NewFunctionState() {
    FunctionState* state = new AddFunctionState(this);
    states.push_back(state);
    return state;
}


int main() {
    Function* func = new PrintFunction();
    Function* func2 = new AddFunction();
    std::vector<Function*> vec = {func, func2};

    for(auto& func : vec) {
        func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
    }

    return 0;
}

现在我已经分析了我的代码,并且已经看到FunctionState :: ExecuteFunctionLotsAndLotsOfTimes()有一个热点。问题是这个函数循环很多次并调用RunState(),它是FunctionState类的虚函数。在那里,我执行了许多操作,这些操作可能会从L1缓存中清除vtable指针,导致循环的每次迭代都会丢失L1缓存。

所以我想删除虚拟呼叫的需要。我决定用CRTP做一个好方法。 FunctionState类将获取实现它的类的类型的模板参数,并调用它的适当方法,不需要对RunState()进行虚拟调用。

现在,当我尝试将其移至CRTP时,我遇到了一些与Function类有关的问题:

  1. 如何转发声明FunctionState类(因为它现在是模板化的)?
  2. 我是否还需要将模板参数添加到Function类中?

    第3。如果我模板化,那么Function对象的构造会是什么样子?如何删除使用Function对象指定类型参数的类的需要?

  3. 请注意,这只是我真实代码库的一个简单版本。真正的代码库是10K +代码行(不是无法管理的,但完全重写是不可能的)。

    此外,如果有另一种方法可以删除不涉及CRTP的RunState()虚拟调用,那么这也是值得赞赏的。

    我尝试使用CRTP:

    #include <iostream>
    #include <vector>
    
    class Function;
    
    template<class T>
    class FunctionState {
    public:
        FunctionState(Function* func) : mFunc(func) {}
    
        void RunState() {
            static_cast<T*>(this)->RunState();
        };
    
        void ExecuteFunctionLotsAndLotsOfTimes();
    private:
        Function* mFunc;
    };
    
    class Function {
    public:
        virtual FunctionState* NewFunctionState() = 0;
    
    protected:
        std::vector<FunctionState*> states;
    };
    
    #define VERY_BIG_NUMBER 10
    
    template <typename T>
    void FunctionState<T>::ExecuteFunctionLotsAndLotsOfTimes() {
        for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
            RunState();
        }
    };
    
    class PrintFunctionState;
    class PrintFunction : public Function {
        PrintFunctionState* NewFunctionState();
    };
    
    class PrintFunctionState : public FunctionState<PrintFunctionState> {
    public:
        PrintFunctionState(PrintFunction* func) : FunctionState<PrintFunctionState>(func) {}
    
        void RunState() {
            std::cout << "in print function state" << '\n';
        }
    };
    
    PrintFunctionState* PrintFunction::NewFunctionState() {
        PrintFunctionState* state = new PrintFunctionState(this);
        states.push_back(state);
        return state;
    }
    
    class AddFunctionState;
    class AddFunction : public Function {
        AddFunctionState* NewFunctionState();
    };
    
    class AddFunctionState : public FunctionState<AddFunctionState> {
    public:
        AddFunctionState(AddFunction* func) : FunctionState<AddFunctionState>(func), x(0) {}
    
        void RunState() {
            ++x;
        }
    private:
        int x;
    };
    
    AddFunctionState* AddFunction::NewFunctionState() {
        AddFunctionState* state = new AddFunctionState(this);
        states.push_back(state);
        return state;
    }
    
    
    int main() {
        Function* func = new PrintFunction();
        Function* func2 = new AddFunction();
        std::vector<Function*> vec = {func, func2};
    
        for(auto& func : vec) {
            func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
        }
    
        return 0;
    }
    

3 个答案:

答案 0 :(得分:2)

基于类型擦除和CRTP的混合解决方案怎么样? 它遵循一个基于问题片段的最小的工作示例:

#include <iostream>
#include <vector>

class PrintFunctionState;
class AddFunctionState;
class FunctionState;

class Function {
    template<typename T>
    static FunctionState * InternalNewFunctionState(Function *self, std::vector<FunctionState*> &states) {
        FunctionState* state = new T(self);
        states.push_back(state);
        return state;
    }

public:
    template<typename T>
    static Function * create() {
        Function *func = new Function;
        func->internalNewFunctionState = &InternalNewFunctionState<T>;
        return func;
    }

    FunctionState* NewFunctionState() {
        return internalNewFunctionState(this, states);
    }

private:
    FunctionState * (*internalNewFunctionState)(Function *, std::vector<FunctionState*> &);
    std::vector<FunctionState*> states;
};

class FunctionState {
public:
    FunctionState() = default;
    virtual ~FunctionState() = default;
    virtual void ExecuteFunctionLotsAndLotsOfTimes() = 0;
};

template<typename Derived>
class IntermediateFunctionState: public FunctionState {
public:
    IntermediateFunctionState(Function* func) : mFunc(func) {}

    void ExecuteFunctionLotsAndLotsOfTimes() override {
        Derived *self = static_cast<Derived *>(this);
        for(int i = 0; i < 10; ++i) {
            self->RunState();
        }
    }

private:
    Function* mFunc;
};

class PrintFunctionState : public IntermediateFunctionState<PrintFunctionState> {
public:
    PrintFunctionState(Function* func) : IntermediateFunctionState(func) {}

    void RunState() {
        std::cout << "in print function state" << '\n';
    }
};

class AddFunctionState : public IntermediateFunctionState<AddFunctionState> {
public:
    AddFunctionState(Function* func) : IntermediateFunctionState(func), x(0) {}

    void RunState() {
        std::cout << "in add function state" << '\n';
        ++x;
    }

private:
    int x;
};

int main() {
    Function* func = Function::create<PrintFunctionState>();
    Function* func2 = Function::create<AddFunctionState>();
    std::vector<Function*> vec = { func, func2 };

    for(auto& func : vec) {
        func->NewFunctionState()->ExecuteFunctionLotsAndLotsOfTimes();
    }

    return 0;
}

我删除了几个不再需要的课程 希望代码说明一切,请在评论中告诉我是否可以添加更多详细信息。

答案 1 :(得分:0)

Function必须使用非模板类型作为NewFunctionState的返回值,因此您需要一个额外的基类

class FunctionStateBase {
    virtual void ExecuteFunctionLotsAndLotsOfTimes() = 0;
    // No void RunState()!
}

template<typename T>
class FunctionState {
    void ExecuteFunctionLotsAndLotsOfTimes();
    // Still no void RunState()!
}

class PrintFunctionState : public FunctionState<PrintFunctionState> {
    void RunState();
}

template <typename T>
void FunctionState<T>::ExecuteFunctionLotsAndLotsOfTimes() {
    for(int i = 0; i < VERY_BIG_NUMBER; ++i) {
        static_cast<T*>(this)->RunState(); // Statically bound!
    }
};

答案 2 :(得分:0)

如果我正确理解您的问题,可以使用模板链接解决这个问题。这是一个很好的例子:

#include <iostream>

/*
    Just make print invocations a little less cluttered for our purposes here.
*/
template <typename Type>
void Show(Type value)
{
    std::cout << value << std::endl;
}

/*
    Base class for function types 
*/
template <typename Self>
class Function 
{
    public:

/*
    For the best performance possible, we'll always inline this function.
*/    
    inline void RunState()
    {
        static_cast<Self*>(this)->RunState();
    }

    void ExecuteFunctionLotsAndLotsOfTimes(int iterations = 1)
    {
        for(int i = 0; i < iterations; ++i)
        {
            Show("...Loop...");    
            RunState();
        }    
    }
};

/*
    Everything here is placed in an internal namespace, as none of it will be used by the caller.
*/
namespace Internal_
{

/*
    ChainFunctionLink works like an array of functions. Each of it's members 
    is either some kind of function object or another ChainFunctionLink.
*/    
template <typename First, typename Second>
struct ChainFunctionLink : Function<ChainFunctionLink<First, Second>>
{
    ChainFunctionLink(First first, Second second)
    : first(first), second(second)
    {    }

    inline void RunState()
    {
        first.RunState();
        second.RunState();
    }

    First
        first;
    Second
        second;
};

/*
    We won't be able to explicitly specify the template parameters of ChainFunctionLink 
    later, so a generating function will be needed to deduce them for us. 
*/
template <typename First, typename Second>
ChainFunctionLink<First, Second> MakeChainFunctionLink(First first, Second second)
{
    return ChainFunctionLink<First, Second>(first, second);
}

} // namespace Internal_

/*
    ChainFunction generates ChainFunctionLink's for the caller.
*/
template <typename First, typename Second, typename ...Next>
auto ChainFunction(First first, Second second, Next ...next)
{
    return Internal_::MakeChainFunctionLink(first, ChainFunction(second, next...));
}

/*
    The last link in the chain.
*/
template <typename Last>
Last ChainFunction(Last last)
{
    return last;
}

// Example usage:

class PrintFunction : public Function<PrintFunction>
{
    public:

    inline void RunState()
    {
        Show("PrintFunction::RunState()");
    }    
};

class AddFunction : public Function<AddFunction>
{
    public:

    inline void RunState()
    {
        Show("AddFunction::RunState()");
    }        
};

int main() 
{
    auto 
        chain = ChainFunction(AddFunction(), AddFunction(), AddFunction(), PrintFunction());
    chain.ExecuteFunctionLotsAndLotsOfTimes(4);      
}

当然,以这种方式将成千上万个功能对象链接在一起可能是不切实际的,但它确实允许你内联(和解耦)几乎所有东西。

修改

该特定类型的实现还有一个警告:链式函数按值 存储 。如果您想避免这种情况,只需重新定义ChainFunctionLink的成员firstsecond作为参考。暂时不允许您将临时值作为参数传递给ChainFunction,当然......