我有一个具有 M 个方法的类,并且只有一个方法对 std::array 执行只读操作。其余的 M-1 方法不使用 std::array。代码如下。假设我无法解散这门课。
我担心的是:
- 这段代码有点难看,因为如上所述,只有 1 个方法使用参数 N。
- 如果我用不同的 N 实例化 Bar 100 次,那么代码不会变得臃肿吗?就像我说的,只有 1 个方法使用参数 N,但我的理解是我将获得 99*(M-1) 个实际上相同方法的额外拷贝。
话虽这么说,使用 vector 或 C 数组来避免模板是标准做法吗?我会牺牲任何潜在的性能吗?
//bar.h
template<int N>
class Bar
{
public:
Bar(const std::array<Foo, N>& arr);
void method_one();
void method_two();
void method_three();
...
private:
const std::array<Foo, N> arr_;
};
template<int N> Bar<N>::Bar(const std::array<Foo, N>& arr) :
arr_(arr)
{}
template<int N> void Bar<N>::method_one()
{
//....
}
template<int N> void Bar<N>::method_two()
{
//....
}
//etc
最佳答案
首先,您的编译器可能(或可能被诱导)折叠相同的函数,即使它们具有不同的签名。
这是否合法(以及如何强制执行),请参见此处:
Do distinct functions have distinct addresses?
Is an implementation allowed to site two identical function definitions at the same address, or not?
接下来,如果模板的成员独立于模板参数,请考虑将它们移至基类:
class Bar_base {
// Move everything here not dependent on template-arguments.
// Can be done multiple times if useful
}
template<int N> class Bar : public Bar_base {
// Everything dependent on `N`, and maybe some using-declarations
// for proper overloading
}
标准库的所有实现都广泛地执行此操作,如果您查看 <iostream>
,它甚至被编入标准中。
关于不使用模板参数的 C++ 模板类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26877675/