部分类模板专业化

时间:2013-04-23 10:04:29

标签: c++ templates template-specialization c++03

我想添加一个成员函数,以防我的类的最后一个模板参数明确地设置为某个值。我不明白如何重新使用之前定义的代码。

我希望编译的简化示例:

template <int A, int B, int C>
struct S
{
  void fun() {}
};

template <int A, int B>
struct S<A,B,0>
{
  void fun1() {}
};

template <int A>
struct S<A,0,0>
{
  void fun2() {}
};

int main()
{
  S<0,0,0> s;
  s.fun();
  s.fun1();
  s.fun2();
  return 0;
}

我需要找到一个使用C ++ 03编译器的解决方案。

1 个答案:

答案 0 :(得分:5)

实际上,您的专业化是非专业化,因为它不专门化任何主要模板的参数:

template<int A, int B>
struct S<A,B> // ...
//       ^^^
//       Does not really specialize the primary template,
//       no specialized pattern is introduced here

您可以尝试以这种方式重写:

template<int A> // <== Only the first template parameter of the primary
                //     template is unconstrained in the pattern we want to
                //     express (the second template argument shall be 1)
struct S<A,1> : public S<A,0>
//       ^^^               ^
// Specializes!            Something meaningful should go here,
//                         but that actually depends on the real
//                         class templates you are using and their
//                         semantics
{
      void fun1() {}
};

作为替代方案,如果您的目标只是有条件地添加一个成员函数,您可以使用SFINAE约束,如下所示而不是专业化:

#include <type_traits> // <== Required for std::enable_if<>

template <class T = void>
//                  ^^^^
//                  The function's return type here
typename std::enable_if<B == 1, T>::type
//                      ^^^^^^
//                      Your condition for the function's existence
fun1()
{
    // ...
}

这是展示这种技术的live example