【问题标题】:return a generic function with specified type返回具有指定类型的泛型函数
【发布时间】:2013-10-26 15:11:23
【问题描述】:

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

【问题讨论】:

  • 你到底想做什么?您如何使用此代码?什么是“问题”/错误?
  • 显式专业化。
  • 没有“泛型类”这样的东西。只有“类模板”。这种误解似乎是许多初学者困惑的根源。
  • 是的,有这样的事情,但是in C#
  • 你能告诉我短语“通用类”和“类模板”有什么区别吗?

标签: c++ class templates generics


【解决方案1】:

下面是一个类模板成员函数的显式特化示例:

#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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2022-12-21
    • 1970-01-01
    相关资源
    最近更新 更多