具有继承的 C++ 模板部分特化

标签 c++ templates c++11 metaprogramming

我需要对 struct 进行部分特化,但我还想使用一些通用功能。例如,假设我有下一个类型:

template <typename A, typename B>
struct Foo  
{
    Foo& func0() { /* common actions with A and B */; return *this; }  
    void func1() { /* common actions with A and B */ }
    void func2() { /* common actions with A and B */ }
}

然后我想专门针对其中一个模板参数 - 例如,当 Bint 时,我想考虑特殊情况,并且我想保留 func0func1 的行为与常见的 Foo 完全相同(当然,func0() 必须返回我的专用 Foo& for int), func2 我想重写(假设我有更有效的整数实现),我还想添加 func3 () 仅适用于我专门的 Foo

当然,我可以简单的写出如下内容:

template <typename A>
struct Foo<A, int>  
{
    Foo& func0() { /* common actions with A and B */; return *this; }  
    void func1() { /* common actions with A and B */ }
    void func2() { /* actions with A and 'int' */ }
    void func3() { /* actions with A and 'int' */ }
}

但我想避免在 func0func1 中复制粘贴。

我也可以将通用的 Foo 重命名为 FooBase 并简单地从中继承 Foo ,但在这种情况下我不能使用常见情况为

Foo<float, float> a;

哪些方法允许我同时使用这两种方法

Foo<float, float> a;

Foo<float, int> b;

没有复制和粘贴通用 Foo 的代码到特化?

我对 c++11 和更早的标准兼容性很感兴趣。

最佳答案

这似乎对我有用。

template <typename A, typename B>
struct Foo;

template <typename A, typename B>
struct FooBase
{
    Foo<A, B>& func0()
    {
        cout << "FooBase:func0\n";
        return static_cast<Foo<A, B>&>(*this);
    }

    void func1() { cout << "FooBase::func1\n"; }
    void func2() { cout << "FooBase::func2\n"; }
};

template <typename A, typename B>
struct Foo : public FooBase<A, B> {
};

template <typename A>
struct Foo<A, int> : public FooBase<A, int>
{
    void func2() { cout << "Foo<A, int>::func2\n"; }
    void func3() { cout << "Foo<A, int>::func3\n"; }
};

如果您最终需要在 FooBase 中定义 Foo,您可能需要使用 CRTP 技巧将派生类作为模板参数传递给 FooBase,但对于简单的事情,我认为前向声明就足够了。

关于具有继承的 C++ 模板部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27453449/

相关文章:

c++ - 将奇怪的十六进制电话号码转换为普通数字

c++ - 在 C++ 中使用函数 JavaScript 样式进行映射

c++ - std::vector 以外的排名保持数据结构?

c++ - 执行同一类的 "Object = object"时出现段错误

c++ - 用于位计数的元程序

c++ - 为库中的 C++ 模板实例强制定义符号

c++ - 尝试使用可变参数模板模仿 python 打印函数不起作用

c++ - 在 C++ 中将数字显式舍入到小数点后 7 位以上

c++ - MSVC 19 删除继承的构造函数

c++ - Stroustrup 关于在函数中传递参数的指南