使用枚举来专门化模板

时间:2012-02-06 11:36:01

标签: c++ templates

我一直在使用带有枚举参数的模板来为我的代码输出提供专门的方法。

template <Device::devEnum d>
struct sensorOutput;

template<>
struct sensorOutput <Device::DEVICE1>
{
    void setData(Objects& objs)
    {
        // output specific to DEVICE1
        // output velocity
        objs.set(VELOCITY, vel[Device::DEVICE1]);
        // output position
        objs.set(POSITION, pos[Device::DEVICE1]);
    }
};

template <>
struct sensorOutput <Device::DEVICE2>
{

    void setData()
    {
        // output specific to DEVICE2
        // output altitude
        objs.set(ALTITUDE, alt[Device::DEVICE2]);
    }
};

我现在想要添加另一个类似于DEVICE1的传感器,它将输出速度和位置。

有没有办法设置多个专业化?我试过了

template <>
struct sensorOutput <Device::DEVICE1 d>
struct sensorOutput <Device::DEVICE3 d>
{

    void setData()
    {
        // output specific to DEVICE1 and DEVICE3
        // output velocity
        objs.set(VELOCITY, vel[d]);
        // output position
        objs.set(POSITION, pos[d]);
    }
};

1 个答案:

答案 0 :(得分:3)

继承怎么样?

template<Device::devEnum d>
struct sensorOutputVeloricyAndPosition
{
    void setData()
    {
        // output specific to DEVICE1 and DEVICE3
        // output velocity
        objs.set(VELOCITY, vel[d]);
        // output position
        objs.set(POSITION, pos[d]);
    }
}


template<>
struct sensorOutput<Device::DEVICE1> : public sensorOutputVeloricyAndPosition<Device::DEVICE1>
{ };

template<>
struct sensorOutput<Device::DEVICE3> : public sensorOutputVeloricyAndPosition<Device::DEVICE3>
{ };
相关问题