Let’s say I have a template function, assign()
. It takes a pointer and a value and assigns the value to the pointer’s target:
template <typename T> void assign(T *a, T b) { *a = b; }
int main() {
double i;
assign(&i, 2);
}
In this case I always want T
to be deduced from the first argument, but it looks like I didn’t do a good job of expressing this. 2
’s type is int
, so:
deduce.cpp:5:5: error: no matching function for call to 'assign' assign(&i, 2); ^~~~~~ deduce.cpp:1:28: note: candidate template ignored: deduced conflicting types for parameter 'T' ('double' vs. 'int') template void assign(T *a, T b) { *a = b; }
Is there a way I can declare assign()
so that the second argument doesn’t participate in template parameter deduction?
T
isstd::vector
. The argumentb
is taken by-value, then copied (not moved) intoa
. A small improvement might be changing the implementation ofassign
to*a = std::move(b)
, which for primitive types costs nothing, and for complex types could save a lot. A large improvement would be to perfect forwardb
. – Yakk - Adam Nevraumont