Reputation: 3207
I have a function f that takes an argument of type Bar, which has 3 template parameters. f doesn't use any of these three parameters. Question: Does the compiler still generate multiple versions of f depending on all of the used combinations of A, B and C, or is there a better way of doing this?
Example:
template<typename A, typename B, typename C>
class Bar;
template<typename A, typename B, typename C>
void f(Bar<A,B,C>& bar)
{
//code that does not use A, B or C, e.g.:
std::cout << bar.some_getter() << std::endl;
}
Upvotes: 0
Views: 106
Reputation: 153830
Whether the compiler will actually generate different code (or any separate code in the first place) will depend on what you are doing with these functions. For example, if you just call the function and it is reasonably small the compiler may entirely inline the code, making it potentially smaller than it would have been if it created a function in the first place.
On the other hand, if you take the address of different instantiations they'll have a different address, i.e., even if the compiler may share much of the identical code, it will need to have different addresses if the types are identical. I'm not sure if you can compare function pointers of different types (our functions will have a different type as the argument Bar<A, B, C>
changes).
Note that even though f()
may not touch any of the types A
, B
, or C
directly, the fact that Bar
can differ between instantiations can result in entirely different code being needed and, obviously, generated.
Upvotes: 4
Reputation: 16737
The compiler will generate exactly the number of overloads you end up using - if your code ends up calling f<A,B,C>
for n
combinations of (A,B,C)
, you will have n
overloads generated. There is no unnecessary bloat. However, template argument deduction happens on exact types. For example, you could have just one function
void foo(double x);
And have both these statements work
foo(1);//int implicitly promoted to double
foo(1.0);
However, if you have
template <typename T>
foo(T x);
you end up generating two overloads.
foo(1);//T is deduced to be int, leading to initialization of foo<int>
foo(1.0);//T is deduced to be double, leading to initialization of foo<double>
Upvotes: 2