本文介绍了元编程单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这取决于枚举的一个单独的类值两个不同的code路径之间进行选择。单例类从一个CSingleton型,其中T是新类的类继承。

I'd like to choose between two different code paths depending on the value of an enum for a singleton class. Singleton classes inherit from a "CSingleton" type, where T is the type of the new class.

enum class Paths
{
    PATH_ONE = 0,
    PATH_TWO,
}

template<Paths pathValue>
class Foo : public CSingleton<Foo>
{
public:
    Foo()
    {
        if(pathValue == Paths::PATH_ONE)
             myValue = 11;
        else if(pathValue == Paths::PATH_TWO)
             myValue = 22;
    }

    int myValue;

};

然后使用一个对象时,我可以做这样的事情:

Then when using an object I could do something like this:

assert(11 == Foo<Paths::PATH_ONE>::Instance().myValue);

要是明确的,实例()是什么将创建对象。

To be explicit, Instance() is what will create the object.

做什么,我试图做有名字吗?是否有或升压的一部分,C ++ 11,可以帮助我吗?

Does what I'm trying to do have a name? Is there a part of Boost or C++11 that can help me out?

谢谢!

推荐答案

您有几个方式做你想要什么在编译的时候它变成模板特:

You have several way to do what you want at compile time which turn into template specialization:

template<Paths> struct MyValue;

template<> struct MyValue<Paths::PATH_ONE> { static constexpr int value = 11; };
template<> struct MyValue<Paths::PATH_TWO> { static constexpr int value = 22; };

所以你有:

Foo() { myValue = MyValue<pathValue>::value; }

2。对于函数

您可以创建几个函数/方法参数化

2. For functions

You may create several functions/method parametrized

template<Paths> void MyAssignVariable(int& var);

template<> void MyAssignVariable<Paths::PATH_ONE>(int& var) { var = 11; };
template<> void MyAssignVariable<Paths::PATH_TWO>(int& var) { var = 22; };

所以你有:

Foo() { MyAssignVariable<pathValue>(myValue); }

和偏专业化是不可能的功能,以下是preferred:

And as partial specialization is not possible on function, the following is preferred:

template<Paths> struct PathSpecialization;

template<> struct PathSpecialization<Paths::PATH_ONE> {
    static void MyAssignVariable(int& variable) { variable = 11; };
    // You may add other methods here.
};
template<> struct PathSpecialization<Paths::PATH_TWO> {
    static void MyAssignVariable(int& variable) { variable = 22; };
    // You may add other methods here.
};

所以你有:

Foo() { PathSpecialization<pathValue>::MyAssignVariable(myValue); }

这篇关于元编程单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 15:52