我正在编写一个升级器,它应该将一个变量arity函数提升到一些类似于带有索引的SQL表的std :: vectors中。我想将f参数应用于所有向量中具有相同id的每组元素。我遇到了模板推导的问题,我在这里提炼它(减去迭代器逻辑)。我写过我认为是一个明智的递归案例,但模板演绎认为它不可行。
// 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
}
这段代码出了什么问题?
为了便于阅读和写作,忽略一切都是通过值传递的。为什么不编译?
答案 0 :(得分:1)
为什么不直接提取A和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)...);
}
此外,您的最后2个测试用例无法编译,因为参数的数量是错误的。
lift(Test<int,int>(), a, a);
lift(Test<int,int,int>(), a, a, b);