gpt4 book ai didi

c++ - 获取模板函数类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:33 26 4
gpt4 key购买 nike

我是在 C++ 中使用模板的新手,我想根据 < 之间使用的类型做不同的事情。和 > , 所以 function<int>()function<char>()不会做同样的事情。我怎样才能做到这一点?

template<typename T> T* function()
{
if(/*T is int*/)
{
//...
}
if(/*T is char*/)
{
//...
}
return 0;
}

最佳答案

您想使用函数模板的显式特化:

template<class T> T* function() {
};

template<> int* function<int>() {
// your int* function code here
};

template<> char* function<char>() {
// your char* function code here
};

关于c++ - 获取模板函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333831/

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