5

我在使用以下代码时遇到了编译问题:

  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;

错误消息是(在标记为“这里”的行上):

error: 'std::vector' is not a type

(当然,我已经包含了来自 std 的向量!)。有什么建议吗?我摆弄了一段时间,但我已经到了可以使用一些帮助的地步:-)我需要部分专门化初始模板声明,以便我可以让编译器根据实际类型切换实现容器 C(将有一个 is_in 用于集合,一个用于向量,一个用于范围......,每次使用不同的算法)。

谢谢!

4

3 回答 3

6

标准不允许函数模板的部分特化。

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

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);
}
于 2011-06-09T19:58:23.740 回答
1

不允许函数模板部分特化。在任何情况下,您都没有使用模板专业化语法,实际上是在编写额外的重载。试试这个:

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

如果允许部分化,它会变成这样:

template <typename T> // std::vector is not a template parameter,
                      // so we wouldn't put it here
bool is_in<T, std::vector>(const std::vector<T>& a, const std::vector<T>& b)
// instead, it'd appear ^ here, when we're specializing the base template
{
    return false; // implementation tbd
}
于 2011-06-09T20:06:28.277 回答
0

我不知道它是否有效(因为模板模板对我来说总是一个麻烦),但是尝试一下怎么样

template <typename T>
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
    ...
}

因为它是一个专业。

编辑:其他人已经对此进行了澄清,但为了完整起见,我会添加它。上面的代码实际上是一个重载而不是偏特化,但是偏函数特化无论如何都是不允许的。

于 2011-06-09T20:01:21.717 回答