功能模板专业化具有模板类
Function template specialization with a template class
可能的重复:
功能模板的部分专业化
我找不到解决问题的解决方案,因为如果我搜索我想出的关键字,就会为我提供适合不同问题的解决方案。我知道之前必须提出过这一点,只是找不到解决方案。
假设我有一个函数模板:
template<class any> print(any value);
我可以这样对此进行专业化,例如 int
:
template<> print<int>(int value)
{
std::cout << value;
}
但是现在问题,我也希望它也可以与向量一起使用。由于矢量类是模板类,因此变得困难。
专门为这样的功能:
template<class any> print<vector<any> >(vector<any> value) {}
将生成以下错误(mingw g ):
FILE: error: function template partial specialization 'print<vector<any> >' is not allowed
请注意,功能打印只是一个示例。
如何解决此问题?
有一个一般的解决方法,其中功能模板只是将作业委派给类模板成员函数:
#include <vector>
#include <iostream>
template <typename T> struct helper {
static void print(T value) { std::cout << value; }
};
template <typename T> struct helper<std::vector<T>> {
static void print(std::vector<T> const &value) { }
};
template <typename T>
void print (T const &value) {
// Just delegate.
helper<T>::print (value);
}
int main () {
print (5);
std::vector<int> v;
print (v);
}
但是,如果您可以通过简单的功能过载(如Ecatmur和Vaughn Cato的建议),请这样做。
不要尝试专业化功能模板。改用过载
void print(int value)
{
std::cout << value;
}
和
template<class any>
void print(vector<any> value) {}
功能模板不允许部分专业化,因为它会导致一定的规则违规。您通常只能使用过载:
template<class any> print(vector<any> value) {}
相关文章:
- 类模板的成员功能的定义在单独的TU中完全专业化
- 特定好友功能专业化
- 如何部分专业化功能以用元组元素作为参数调用功能
- 功能模板参数包,然后是模板参数和专业化
- 不允许功能模板的部分专业化背后的理由是什么?
- 在此功能[ - wuninitialization]中使用非专业化
- 模板专业化的情况下,如果有变态模板功能
- 如何在另一个名称空间内从另一个命名空间内明确专业化功能模板
- 为什么VS2017拒绝我的功能模板专业化,而不是VS2015拒绝
- 仅适用于单个功能的部分模板专业化
- 功能模板专业化具有模板打字名称
- 对完整模板专业类成员功能的未定义引用,但不是部分专业化
- 特定模板类型的功能模板专业化
- 功能模板专业化中的bool返回值
- C 将lambda函数用作模板功能专业化
- 如何正确设计和实施功能模板专业化
- Clang无法在模板类专业化中编译模板功能,该模板类专业化与模板声明具有 *不同的返回类型 *
- 统一功能使用模板专业化和接口来调用实例和原始类型
- 当使用Tempate作为参数时,功能模板专业化
- 模板功能实例化和专业化