我有一个包含M个方法的类,只有一个方法对std :: array执行只读操作。其余的M-1方法不使用std :: array。代码如下。假设我无法分手。
我担心的是:
话虽这么说,使用矢量或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
答案 0 :(得分:2)
首先,即使编辑器具有不同的签名,您的编译器也可能(或可能被诱导)折叠相同的功能 这是否合法(以及如何强制),请参见此处:
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>
,它甚至可以在标准中编写。
答案 1 :(得分:0)
如果只有构造函数使用std :: array&lt; ...,N&gt;你可以将模板化的类转换为带有模板化构造函数的标准类。还有更多我希望编译器足够聪明,不能复制100个没有依赖N的代码片段。
class Bar
{
public:
template<int N>
Bar(const std::array<Foo, N>& arr);
...
...
}
编辑:废话!!这似乎没有编译......它适用于像这样的参数
class Bar {
public:
template<int N>
Bar(const int (& a)[N]);