特定类模板类型的模板化类方法的不同实现

ray*_*mag 5 c++ templates

我有一个带有方法的模板化类,我需要针对特定​​模板类型的不同实现。我该如何完成?

Tim*_*sch 5

您必须为此特定类型创建部分(或全部)专业化

  • 但是,您必须专门化整个类型,而不能仅部分专门化成员函数。这在答案中是隐含的,但可能会被误解。 (5认同)

jon*_*son 3

您可以专门针对该类型的方法。例如

template<typename T>
struct TemplatedClass
{
    std::string methodA () {return "T methodA";}

    std::string methodB () {return "T methodB";}
    std::string methodC () {return "T methodC";}
};

// Specialise methodA for int.

template<>
std::string TemplatedClass<int>::methodA ()
{
    return "int methodA";
}
Run Code Online (Sandbox Code Playgroud)