C++ 模板化类的模板专门化
我一直在研究许多其他关于模板专门化的问题,但我似乎找不到问题的答案。我已经读到,你不能部分专门化函数模板。那么接下来的工作是什么呢 考虑一个名为C++ 模板化类的模板专门化,c++,templates,C++,Templates,我一直在研究许多其他关于模板专门化的问题,但我似乎找不到问题的答案。我已经读到,你不能部分专门化函数模板。那么接下来的工作是什么呢 考虑一个名为type的函数。此函数用于返回一个表示其类型的char。在构建类时,必须“重载”或专门化函数type,以便名为print\u type的函数可以打印对象的类型,而无需调用函数type。下面是一些代码: #include <cstdio> #include <string> #include <vector> temp
type
的函数。此函数用于返回一个表示其类型的char
。在构建类时,必须“重载”或专门化函数type
,以便名为print\u type
的函数可以打印对象的类型,而无需调用函数type
。下面是一些代码:
#include <cstdio>
#include <string>
#include <vector>
template<class T> inline char type(const T&) {return 'S';}
template<> inline char type(const int&) {return 'I';}
template<> inline char type(const double&) {return 'R';}
template<class T>
void print_type(T& t) {
printf("Type = %c\n", type(t));
}
// OTHER FUTURE TYPES
template<> inline char type(const std::string&) {return 'W';}
template<class T> inline char type(const std::vector<T>&) {return 'T';}
int main() {
int x;
printf("Int type: %c\n", type(x));
print_type(x);
double y;
printf("Double type: %c\n", type(y));
print_type(y);
std::string str;
printf("String type: %c\n", type(str));
print_type(str);
std::vector<int> vtor;
printf("Vector type: %c\n", type(vtor));
print_type(vtor);
}
print_type
函数无法获取std::vector
的定义,它只是默认为我定义的原始模板函数。有什么办法可以解决这个问题?请记住,我必须能够在可能的将来为一些其他未知类型定义类型
,因此在设置了类型
的所有定义后,我无法声明函数打印类型
。无法部分专门化函数模板的规范解决方法是委托到部分专用的类模板,可能带有合适的静态
成员函数。例如:
template <typename> struct type_aux { static char type() { return 'S'; } };
template <> struct type_aux<int> { static char type() { return 'I'; } };
template <> struct type_aux<double> { static char type() { return 'R'; } };
template <> struct type_aux<std::string> { static char type() { return 'W'; } };
template <typename T> struct type_aux<std::vector<T>> {
static char type() { return 'T'; }
}
template <typename T> char type(T const&) { return type_aux<T>::type(); }
template struct type_aux{static char type(){return'S';};
模板结构类型_aux{static char type(){return'I';};
模板结构类型_aux{static char type(){return'R';};
模板结构类型_aux{static char type(){return'W';};
模板结构类型{
静态字符类型(){return'T';}
}
模板字符类型(T常量&){返回类型_aux::type();}
只是为了解释为什么您的方法不能按您编写的方式工作:函数模板
模板字符类型(std::vector const&)
需要在print\u type()
的实例化过程中找到。然而,在这一点上,函数只能通过依赖于参数的查找找到,而不会查找定义它的地方。如果您在命名空间std
中声明了函数模板,则可以找到它,但不允许这样做。专门化方法完全回避了必须定位函数的问题。这样做会带来很大的开销吗?我想我会将其用于无法专门化的对象,比如std::vector
。对于std::string
,我们可以简单地专门化函数类型。谢谢。请在type_aux
@jmlopez中添加一些空间:如果将成员设置为静态
内联
,则根本不会有任何运行时开销。符号名的占用空间可能会更大,但实际上并没有那么大(这是否重要取决于您使用这些无法内联的函数的频率)。@jmlopez:是的,如果您需要使用C++03编译器进行编译,则需要在>
之间留出一个空格。然而,使用C++11(2年多以来的现行标准),空间是不必要的。问题,静态函数是否已经内联,因为它们是在结构内部定义的?我认为如果将它们的实现放在声明之外,它们就不能内联。