我正在尝试编写一个通用过滤函数,该函数在多维数组(任意秩)中的给定采样坐标处执行线性插值。为此,我需要一个递归函数模板,它遍历数组的所有维度,直到找到一个值及其关联类型。我使用 boost::enable_if 来检测何时停止遍历维度。在我尝试将返回值/类型“渗透”到最顶层函数之前,它可以正常工作。为此,我尝试使用 C++0x 类型推断,但它似乎与 boost::enable_if 不能很好地混合。
我将问题分解为以下内容:
template< typename T, std::size_t I >
auto test(const T &t) -> typename boost::enable_if_c< (I == 0), typename T::value_type >::type
{
return t[0];
}
template< typename T, std::size_t I >
auto test(const T &t) -> typename boost::enable_if_c< (I > 0), decltype(test< T, I - 1 >(T())) >::type
{
return test< typename T::value_type, std::size_t(I - 1) >(t[0]);
}
编译器(GCC 4.6)抱怨以下代码:
typedef std::array< std::array< float, 1 >, 1 > myarray;
myarray ma;
std::cout << typeid (test< myarray, 1 >(ma)).name() << std::endl;
错误信息:
error: conversion from 'boost::enable_if_c<true, float>::type' to non-scalar type 'boost::enable_if_c<true, std::array<float, 1u> >::type' requested
似乎 decltype 使用来自 test< T, I > 的返回值,即使它被指示使用 test< T, I - 1 > 的返回值。知道为什么会发生这种行为吗?现在,它想我会把整个东西变成一个仿函数......