gpt4 book ai didi

c++ - 模板特化和继承

转载 作者:IT老高 更新时间:2023-10-28 12:59:13 27 4
gpt4 key购买 nike

假设我有一个包含很多函数的模板类,我想对它们进行专门化,只更改其中的一部分,而让其他的完全按照基本模板类中的指定。

我该怎么做?

以下是我想要实现的,但解决方案不好,因为它不允许我引用 int 的特化作为 Base<int> – 我需要使用 IntSpec为此。

#include <iostream>

using namespace std;

template<typename T>
struct Base
{
void print1() {cout << "Base::print1" << endl;};
void print2() {cout << "Base::print2" << endl;};
};

struct IntSpec : public Base<int>
{
void print2() {cout << "Base<int>::print2()" << endl;};
};

int main()
{
Base<double> d;
// Base<int> i; <-- I want this kind of instantiation
IntSpec i;

d.print1();
d.print2();
i.print1();
i.print2();
}

输出是:

Base::print1
Base::print2
Base::print1
Base<int>::print2()

最佳答案

Nicol 的解决方案效果很好,但这是另一种选择:

template<typename T>
struct Base
{
void print1() {cout << "Base::print1" << endl;};
void print2() {cout << "Base::print2" << endl;};
};

template<>
void Base<int>::print2() {cout << "Base<int>::print2()" << endl;};

这样您就可以只专门化特定的成员函数,并且仍然可以毫无问题地使用那些您没有专门化的成员函数(在本例中为 print1)。所以现在你可以随心所欲地使用它了:

Base<int> i;
i.print1();
i.print2(); // calls your specialization

演示 here .

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com