如何专门用于模板模板参数

时间:2017-10-02 21:49:36

标签: c++ templates

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

考虑以下简单示例

#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模板参数)?

谢谢!

2 个答案:

答案 0 :(得分: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(); }

答案 1 :(得分:0)

另一种方法是标签调度:

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>{});
}
相关问题