繁体   English   中英

返回具有指定类型的泛型函数

[英]return a generic function with specified type

如果我有一个类型为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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM