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

标签 c++ class templates generics

如果我有一个类型为 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/

相关文章:

c++ - shared_ptr 对容器的意义是什么?

c++ - 不会删除指针

python - python中的实例

c++ - 使用模板元编程将模板函数 bool 参数转置为运行时函数参数

c++ - C++ 语法的两个好奇心

javascript - 如果类(class)也是类(class),那么..单击时移动事件类(class)

python - pickle 一个动态参数化的子类

c++ - 使用类模板需要模板参数列表链接列表

c++ - “Overload” 基于C++98中函数对象operator()签名的函数模板

c++ - 专门用于一组值的模板