c++ - 除模板参数外具有相同功能的模板特化

标签 c++ templates specialization

如何在不使用宏的情况下处理以下 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/

相关文章:

c++ - 如何在 Windows 上编译 Clang

c++ - 0xC00000FD(堆栈溢出)错误的参数是什么?

c++ - 模板模板和部分特化 : a puzzle

c++ - 模板特化还是条件表达式?

c++ - "Define"类构造函数中的成员函数

c++ - QT 位置类

c++ - 模板类和 Friend 模板函数

C++ 函数嵌套模板

c++ - 使用默认参数专门化内部模板

c++ - 特定成员的模板特化?