![](/img/trans.png)
[英]How to specialize a variadic template struct for particular number of template arguments
[英]How to specialize for template template arguments
我想使用模板类型专门化一个函数,但我无法获得所需的结果。
考虑以下简单示例
#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 <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(); }
另一种方法是标签调度:
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>{});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.