gpt4 book ai didi

c++ - 返回指定类型的泛型函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:43:59 25 4
gpt4 key购买 nike

如果我有一个类型为 T 的泛型类,并且我有一个返回 T 的函数,如果 typeid(T) == typedef(string),我希望我的函数返回一个特定的字符串怎么办?

template<class T>
class Class1
{
public:
Class1();
~Class1();
T func();
};


template <class T>
T Class1<T>::func()
{
string d = "T = string";
if (typeid(string) == typeid(T))
return (T)d; <-- here I got the problem
}

最佳答案

这是一个类模板的成员函数显式特化的例子:

#include <iostream>
#include <string>

template<class T>
class Class1
{
public:
Class1() {}
~Class1() {}
T func();
};


template <class T>
T Class1<T>::func()
{
std::cout << "non-specialized version\n";
return T();
}

template<>
std::string Class1<std::string>::func()
{
std::cout << "string version\n";
return "woot";
}

int main()
{
Class1<int>().func();
Class1<std::string>().func();
}

关于c++ - 返回指定类型的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19608256/

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