【问题标题】:How to specialize for template template arguments如何专门化模板模板参数
【发布时间】:2017-10-02 21:49:35
【问题描述】:

我想使用模板类型专门化一个函数,但我无法获得所需的结果。

考虑以下简单示例

#include <iostream>
#include <typeinfo>
#include <vector>


template <typename T>
void foo(){
    std::cout << "In foo1 with type: " << typeid(T).name() << std::endl;
}

template< template<class, class...> class VEC, typename T>
void foo(){
    std::cout << "In foo2 with vec type: " << typeid(VEC<T>).name()
              << " and template type: " << typeid(T).name() << std::endl;
}


int main() {
    foo<int>();
    foo<std::vector, int>();
    foo<std::vector<int>>(); // Would like this to call the second version of foo
}

它的输出是

In foo1 with type: i
In foo2 with vec type: St6vectorIiSaIiEE and template type: i
In foo1 with type: St6vectorIiSaIiEE

有没有办法为 foo 的第二个版本编写模板签名,用于最后一次调用 foo(使用 std::vector 模板参数)?

谢谢!

【问题讨论】:

  • 您想要:template&lt;&gt; void foo&lt;std::vector&lt;int&gt;&gt;(){ std::cout &lt;&lt; "In specialized foo1 with vec type: " &lt;&lt; typeid(VEC&lt;int&gt;).name() &lt;&lt; " and template type: " &lt;&lt; typeid(int).name() &lt;&lt; std::endl; } 吗?
  • @Jarod42 我想要更通用的东西

标签: c++ templates


【解决方案1】:

由于您不能部分专门化函数模板,通常的方法是使用帮助类模板:

template <typename T> struct X
{
    static void f() { std::cout << "Primary\n"; }
};

template <template <typename...> class Tmpl, typename T>
struct X<Tmpl<T>>
{
    static void f() { std::cout << "Specialized\n"; }
};

template <typename T> void foo() { X<T>::f(); }

【讨论】:

  • 这就是我想要的。谢谢!
  • @acorso:没问题 :-)
【解决方案2】:

另一种方法是标签调度:

template <typename> struct Tag{};

template <typename T> void foo(Tag<T>) { std::cout << "generic\n"; }

template <typename T> void foo(Tag<std::vector<T>>) { std::cout << "vector\n"; }


template <typename T> void foo()
{
    foo(Tag<T>{});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多