c++ - 继承成员函数的模板特化

标签 c++ templates

我们想专门化基类的成员函数。但是,它不编译。有人知道可以编译的替代方案吗?

举个例子

struct Base
{
    template<typename T>
    void Foo()
    {
        throw "Foo() is not defined for this type";
    }
};

struct Derived : public Base
{
    template<>
    void Foo<int>() { cout << "Foo<int>()" << endl; } // compile error (cannot specialize members from a base class)

    template<>
    void Foo<double>() { cout << "Foo<double>()" << endl; }  // compile error (cannot specialize members from a base class)
};

最佳答案

最终,我们使用重载解决了它。

这是基类的样子

struct Base
{
    template<typename T>
    class OfType {}

    template<typename T>
    void Foo(OfType<T>) { static_assert(false, "Foo is not implemented for this type. Please look in the compiler error for more details."); }
};

struct Derived : public Base
{
    using Base::Foo;

    void Foo(OfType<int>) { // here comes logic for ints }
    void Foo(OfType<double>) { // here comes logic for doubles }
};

这是一个使用 Foo()

的客户端代码示例
template<typename S>
class ClassThatUsesFoo
{
    private: S s;

    template<typename T>
    void Bar(T item) 
    {  
        s.Foo(Base::OfType<T>());  // this is the code that uses Foo
        DoSomeStuffWithItem(item); 
    } 
};

void main()
{
    ClassThatUsesFoo<Derived> baz;
    baz.Bar(12); // this will internally use Foo for ints
    baz.Bar(12.0); // this will use Foo for doubles
    baz.Bar("hello world"); // this will give a verbose compile error
}

关于c++ - 继承成员函数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12937881/

相关文章:

c++ - Openmp 原子和关键

java - 一个函数应该属于两个类中的一个/两个还是独立的?

c++ - 已删除 "general"案例的专用模板函数无法使用 g++ <=4.8.0 和 clang++ 编译

c++ - 表达式未评估为常量两级 constexpr 函数(编译器错误?)

c++ - 返回指针变成垃圾...c++

c++ - 如何防止 boost logger 在每条记录后添加\n?

c++ - 可变参数模板和 std::array 意外行为

json - Golang直接在模板中使用json

c++ - 如何新建模板特化类对象?

c++ - 如何写出可以和Eigen抗衡的matrix矩阵乘积?