gpt4 book ai didi

c++ - 模板部分特化 : How can code duplication be avoided?

转载 作者:可可西里 更新时间:2023-11-01 17:56:40 25 4
gpt4 key购买 nike

当模板完全专用时,不需要复制成员函数。例如,在以下代码中,foo()只写一次。

#include <iostream>

template<int M>
class B
{
public:
void foo();
private:
void header();
};

template<int M>
void
B<M>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << M << std::endl;
}

template<int M>
void
B<M>::header()
{
std::cout << "general foo()" << std::endl;
}

template<>
void
B<2>::header()
{
std::cout << "special foo()" << std::endl;
}

但是,对于偏特化,需要复制类定义和所有成员函数。例如:

#include <iostream>

template<int M, int N>
class A
{
public:
void foo();
private:
void header();
};

template<int M, int N>
void
A<M, N>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << M << ", N = " << N << std::endl;
}

template<int M, int N>
void
A<M, N>::header()
{
std::cout << "general foo()" << std::endl;
}

template<int N>
class A<2, N>
{
public:
void foo();
private:
void header();
};

template<int N>
void
A<2, N>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << 2 << ", N = " << N << std::endl;
}

template<int N>
void
A<2, N>::header()
{
std::cout << "special foo()" << std::endl;
}

注意 A<2, N>::foo() A<M, N>::foo() 的拷贝用 2 手动替换 M .

如何在模板偏特化的上下文中避免此类代码重复?

最佳答案

在这种情况下,我会创建一个不知道模板参数“N”的基类:

#include <iostream>

template<int M>
class ABase
{
protected:
void header();
};

template<int M>
void
ABase<M>::header()
{
std::cout << "general header()" << std::endl;
}


template<>
void ABase<2>::header()
{
std::cout << "special header()" << std::endl;
}

template<int M, int N>
class A : private ABase<M>
{
public:
void foo();
};

template<int M, int N>
void
A<M, N>::foo()
{
// specialized code:
this->header();
// generic code:
std::cout << "M = " << M << ", N = " << N << std::endl;
}

int main()
{
A<1,0> a1;
a1.foo();

A<2,0> a2;
a2.foo();
}

或者,您可以特化整个基类。

关于c++ - 模板部分特化 : How can code duplication be avoided?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34998448/

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