gpt4 book ai didi

c++ - 如何检查我的模板类是否属于特定的类类型?

转载 作者:IT老高 更新时间:2023-10-28 12:55:12 26 4
gpt4 key购买 nike

在我的模板化函数中,我试图检查类型 T 是否属于特定类型。我该怎么做?

p/s 我知道模板规范的方式,但我不想这样做。

template<class T> int foo(T a) {
// check if T of type, say, String?
}

谢谢!

最佳答案

使用特化代替检查类型。否则,不要使用模板。

template<class T> int foo(T a) {
// generic implementation
}
template<> int foo(SpecialType a) {
// will be selected by compiler
}

SpecialType x;
OtherType y;
foo(x); // calls second, specialized version
foo(y); // calls generic version

关于c++ - 如何检查我的模板类是否属于特定的类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2265381/

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