如何在不使用宏的情况下处理以下 Object::func() 定义的重复?
template <int N> struct Object {};
template <> struct Object<0> {
// special stuff
void func();
};
template <> struct Object<1> {
// special stuff
void func();
};
template <> struct Object<2> {
// special stuff
void func();
};
template <int N> struct Thing {};
void Object<0>::func() {
Thing<0> a;
// do stuff with a
}
void Object<1>::func() {
Thing<1> a;
// do exact same stuff with a
}
void Object<2>::func() {
Thing<2> a;
// do exact same stuff with a
}
私有(private)继承,基类有模板 int N?元模板的东西?阴极射线管?我想不通。注意
// special stuff
意味着模板特化是必要的——我只是没有展示它们是如何特化的。我只展示了一个与所有函数几乎相同的函数 func()。
最佳答案
使用继承可以避免对通用代码进行特化。怎么样:
template <int N> struct ObjectBase {
void func();
};
template <int N> struct Thing {};
template <int N>
void ObjectBase<N>::func() {
Thing<N> a;
// do stuff with a
}
template <> struct Object<0>: private ObjectBase<0> {
// special stuff
};
template <> struct Object<1>: private ObjectBase<1> {
// special stuff
};
template <> struct Object<2>: private ObjectBase<2> {
// special stuff
};
关于c++ - 除模板参数外具有相同功能的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24653852/