对于需要其他模板参数的类型函数的部分模板专业化
Partial template specialization of a function for a type which needs additional template parameters
i具有内部包含数组的类型。我需要一个函数,如果类型不是。
这是代码:
#include <cstdio>
template<typename T, unsigned n>
struct A
{
T values[n];
};
template<typename T>
unsigned count_components()
{
return 1;//all types except 'A' should have 1 component
}
template<typename T, unsigned n>
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
{
return n;
}
int main()
{
printf("%dn", count_components<A<float, 4> >());//should be 4
printf("%dn", count_components<float>());//should be 1
return 0;
}
g 错误:
test.cpp:13:37: error: function template partial specialization ”count_components<A<T, n> >” is not allowed
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
^
当我有功能时,我更喜欢留下功能(这对成员函数更有益,因为您仍然可以访问*this
)。
template<typename T, unsigned n>
unsigned count_components_switch(boost::mpl::identity<A<T, n>>)
{
return n;
}
template<typename T>
unsigned count_components_switch(boost::mpl::identity<T>)
{
return 1;
}
template<typename T>
unsigned count_components()
{
return (count_components_switch)(boost::mpl::identity<T>());
}
函数不能部分专业。相反,您可以使用可以部分专业化的类:
#include <cstdio>
template<typename T, unsigned n>
struct A
{
T values[n];
};
template<typename T>
struct component_counter
{
static unsigned count()
{
return 1;
}
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
static unsigned count()
{
return n;
}
};
int main()
{
printf("%dn", component_counter<A<float, 4> >::count());//should be 4
printf("%dn", component_counter<float>::count());//should be 1
return 0;
}
,在这种情况下,count()实际上根本不必是一个函数!您可以这样做:
#include <cstdio>
template<typename T, unsigned n>
struct A
{
T values[n];
};
template<typename T>
struct component_counter
{
static const unsigned count=1;
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
static const unsigned count=n;
};
int main()
{
printf("%dn", component_counter<A<float, 4> >::count);//should be 4
printf("%dn", component_counter<float>::count);//should be 1
return 0;
}
这是较少的代码。注意的是,计数必须是一种积分类型才能使其起作用。
相关文章:
- 函数模板部分专业化-有什么解决方法吗
- 我应该声明我的函数模板专业化还是定义它们就足够了
- std::转换move构造函数的模板专业化的变体
- 常量函数参数的专业化
- 纯虚函数的模板专业化
- 删除模板函数,除了它的一个专业化
- 为什么这不是函数模板的部分专业化
- 在允许的函数模板的明确专业化中扣除了多个模板参数
- 使用声明类型选择函数专业化
- 关于函数的完整专业化的名称查找的漫画
- C - 具有非类型模板参数的模板类上的专业化函数模板
- C++11性能:Lambda内联与函数模板专业化
- 为什么不允许对成员函数的模板专业化
- 成员函数模板参数的部分专业化
- C 将lambda函数用作模板功能专业化
- 对于需要其他模板参数的类型函数的部分模板专业化
- 特定成员函数的部分专业化
- 指针作为函数返回类型的部分专业化
- 为什么未经声明未从.cpp文件拾取模板函数的完整专业化
- 模板成员函数专业化