Reputation: 5471
I'm writing a lifter that should lift a variable arity function into some std::vectors that resemble an SQL table with an index. I want to apply the f parameter to each set of elements having the same id across all the vectors. I'm having a problem with template deduction and I have distilled it here (minus the iterator logic). I have written what I think is a sensible recursive case but template deduction thinks it not viable.
// Simple container type
template <typename T>
struct A {
T x;
T y;
T z;
};
// Wrapper type to differentiate an extracted value from a container
// in template deduction
template <typename T>
struct B {
T value;
};
// Base case. All A<Ts> have been extracted to B<Ts>.
template <typename F, typename... Ts>
void lift (F f, B<Ts> ...bs) {
// Call f with extracted values
f(bs.value...);
}
// Recursive case
template <typename F, typename T, typename... Ts, typename Us>
void lift (F f, A<T> a, A<Ts> ...as, B<Us> ...bs) {
// Copy a value from the beheaded container A<T>.
B<T> b = {a.x};
// Append this B<T> to args and continue beheading A<Ts>.
lift(f, as..., bs..., b);
}
// Test function
template <typename... Ts>
struct Test {
void operator () (Ts...) {}
};
int main () {
B<int> b = {1};
// No errors for the base case
lift(Test<>());
lift(Test<int, int>(), b, b);
// error: no matching function for call to 'lift'
// The notes refer to the recursive case
A<int> a = {1,0,0};
lift(Test<int>(), a); // note: requires at least 3 arguments, but 2 were provided
lift(Test<int>(), a, a); // note: requires 2 arguments, but 3 were provided
lift(Test<int>(), a, a, b); // note: requires 2 arguments, but 4 were provided
}
What's wrong with this code?
Ignoring that everything is pass by value here for ease of reading and writing. Why wont this compile?
Upvotes: 3
Views: 149
Reputation: 523484
Why not simply directly extract the values of A and B?
template <typename T>
T extractValue(A<T> a)
{
return a.x;
}
template <typename T>
T extractValue(B<T> b)
{
return b.value;
}
template <typename F, typename... T>
void lift (F f, T... values) {
f(extractValue(values)...);
}
Also, your last 2 test cases cannot compile because the number of arguments are wrong.
lift(Test<int,int>(), a, a);
lift(Test<int,int,int>(), a, a, b);
Upvotes: 1