2012-02-06 139 views
4

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

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]); 
    } 
}; 

回答

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> 
{ };