我在使用以下代码进行编译时遇到麻烦:

  template <typename T,
            template <class T, class Allocator = std::allocator<T> > class C>
  bool is_in(const C<T>& a, const C<T>& b);

  template <typename T, std::vector> // HERE
  bool is_in(const std::vector<T>& a, const std::vector<T>& b)
  {
    return false; // implementation tbd
  }

...

vector<int> a, b;

cout << is_in(a,b) << endl;

错误消息是(在标记为“HERE”的行上):
error: 'std::vector' is not a type

(当然,我包括了来自std的 vector !)。有什么建议吗?我花了一段时间,但我已经可以使用一些帮助了:-)我需要部分专门化初始模板声明,以便可以根据实际的类型来进行编译器切换容器C(集合中有一个is_in, vector 有一个is_in,范围有一个is ...,每次都有不同的算法)。

谢谢!

最佳答案

标准不允许功能模板的部分特化。

一个简单的解决方案是:使用重载。

template <typename T>
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
  return false; // implementation tbd
}

这是重载的功能模板。它不是部分特化的。

或者,您可以这样做:
namespace detail
{
    template<typename T, typename C>
    struct S
    {
        static bool impl(const C & a, const C & b)
        {
            //primary template
            //...
        }
    }
    template<typename T>
    struct S<T, std::vector<T> >
    {
        static bool impl(const std::vector<T> & a, const std::vector<T> & b)
        {
            //partial specialization for std::vector
            return false;
        }
    }
}

template <typename T,  template <class T, class Allocator = std::allocator<T> > class C>
bool is_in(const C<T>& a, const C<T>& b)
{
   return detail::S<T, C<T> >::impl(a,b);
}

07-24 09:45
查看更多