问题
I have a class with M number of methods, and only one method performs read-only operations on a std::array. The rest of the M-1 methods do not use the std::array. Code below. Assume I can't break up this class.
My concerns are:
- This code is little ugly because, as mentioned, only 1 method uses the parameter N.
- If I instantiate Bar 100 times each with different N's, then doesn't that bloat the code? Like I said, only 1 method uses the parameter N, yet my understanding is that I'll get 99*(M-1) extra copies of effectively the same method.
That being said, is it standard to use a vector or a C-array instead to avoid template? Will I be sacrificing any potential performance?
//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
回答1:
First, your compiler might (or might be induced to) fold identical functions even if they have different signatures.
Whether that is legal (and how to force it), see here:
Do distinct functions have distinct addresses?
Is an implementation allowed to site two identical function definitions at the same address, or not?
Next, if members of your template are independent of template-arguments, consider moving them to a base-class:
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
}
All implementations of the standard library do it extensively, and if you look at <iostream>, it's even codified in the standard.
回答2:
If only the constructor uses std::array<...,N> you may turn your templated class into a standard class with templated constructor. Further more I would hope that the compiler is clever enough to not copy 100s of code fragment that do not have any dependency on N.
class Bar
{
public:
template<int N>
Bar(const std::array<Foo, N>& arr);
...
...
}
EDIT: Crap !! This doesn't seem to compile... It works with parameters like
class Bar {
public:
template<int N>
Bar(const int (& a)[N]);
来源:https://stackoverflow.com/questions/26877675/c-template-class-methods-that-do-not-use-template-parameter