gpt4 book ai didi

c++ - 模板化类的模板特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:49 28 4
gpt4 key购买 nike

我一直在查看许多其他关于模板特化的问题,但我似乎找不到问题的答案。我读过你不能部分特化函数模板。那么下面的解决方法是什么。

考虑一个名为 type 的函数.此函数旨在返回单个 char表示它的类型。在构建类时,您将不得不“重载”或专门化函数 type这样一个名为 print_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);
}

注意我已经定义了专门的type对于 std::string .不知何故,似乎无法处理 std::vector<T>某种类型的T .运行上述代码的结果为:

macbook-pro:~ jmlopez$ ./a.out 
Int type: I
Type = I
Double type: R
Type = R
String type: W
Type = W
Vector type: T
Type = S

print_type函数无法获取 std::vector<std::string> 的定义它只是默认为我定义的原始模板函数。解决这个问题的方法是什么?请记住,我必须能够定义 type对于某些可能的 future 其他未知类型,因此我无法声明函数 print_type在所有 type 的定义之后已设置。

最佳答案

无法部分特化函数模板的规范解决方法是委托(delegate)给部分特化的类模板,可能使用合适的 static成员函数。例如:

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 <typename T> char type(std::vector<T> const&)需要在 print_type() 的实例化期间找到.但是,此时只能通过参数相关查找找到函数,而不会查找您定义它的位置。如果您在 namespace std 中声明了函数模板,则可以找到它但你不能这样做。特化方法完全回避了必须定位功能的问题。

关于c++ - 模板化类的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21030747/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com