如何专门用于模板模板参数
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 << "Primaryn"; }
};
template <template <typename...> class Tmpl, typename T>
struct X<Tmpl<T>>
{
static void f() { std::cout << "Specializedn"; }
};
template <typename T> void foo() { X<T>::f(); }
替代方案是标签派遣:
template <typename> struct Tag{};
template <typename T> void foo(Tag<T>) { std::cout << "genericn"; }
template <typename T> void foo(Tag<std::vector<T>>) { std::cout << "vectorn"; }
template <typename T> void foo()
{
foo(Tag<T>{});
}
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 使用在用于SFINAE的void_t中具有参数的方法
- 用于检查值是否为其任何参数的帮助程序函数
- 为什么可变参数函数不适用于模板
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 一个模板方法,用于同时接受常量和非常量参数
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么模板参数推导不适用于仅指定前两个参数的可变参数模板类?
- 隐式生成的函数重载用于右值参数?
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 将非 const 对象用于 const 参数
- 我可以将模板中的类型参数用于非类型参数吗?
- opencl openGL互操作内核参数用于读取 写入
- 分配参数用于测试目的
- 将命令行参数用于输入参数
- 如何使用类的属性作为模板参数/用于专用化
- 为什么我不能将此参数用于 std::sort() 的比较?
- 模板类参数用于模板类函数语法
- 为什么 GCC 不允许我将模板参数用于另一个模板的参数?