【问题标题】:template template parameter for stl containers behaving different from custom template classstl 容器的模板模板参数与自定义模板类的行为不同
【发布时间】:2016-11-03 23:54:42
【问题描述】:

我有以下结构和功能

template <class T> struct C {};

template <template <class S> class T, class U> void f() { T<U> tu; }

当用C 模板化f() 时,我没有收到错误,当用std::vector 模板化它时我会。

int main() {
  f<C, int>();
}

没有错误

int main() {
    f<std::vector, int>();
}

产量

error: no matching function for call to 'f'
f<std::vector, int>();
^~~~~~~~~~~~~~~~~~~~~~~~
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'T'
template <template <class S> class T, class U> void f() { T<U> tu; }

这里Cstd::vector有什么区别?

【问题讨论】:

    标签: c++ templates stl template-templates


    【解决方案1】:

    这是因为vector 有两个模板参数,而不是一个(TAllocator)。

    您可以更改您的 f 模板以接受两个模板参数(或可变参数包):

    template <template <class...> class T, class U> void f() { T<U> tu; }
    

    或者您可以将 vector 别名为 1 参数模板:

    template<typename T>
    using vec = std::vector<T>;
    

    【讨论】:

      【解决方案2】:

      不同之处在于vector有两个模板参数,而不是一个。要解决此问题,您可以使用

      template <template <class... S> class T, class U> void f() { T<U> tu; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 2020-12-15
        • 1970-01-01
        相关资源
        最近更新 更多