我该怎么写一个像MPL中那样工作的元函数呢

How am I supposed to write a metafunction that works like the ones in MPL?

本文关键字:MPL 工作 函数 一个      更新时间:2023-10-16

当我试图编写一个调用MPL代码的元函数时,我似乎缺少了一些东西。以下代码在inst2上编译失败,出现以下错误,但在inst1上运行良好:

错误C2903:"apply":符号既不是类模板也不是函数模板

using namespace boost::mpl;
template <typename VECTOR>
struct first_element : mpl::at_c<VECTOR, 0> {};
int main()
{
    typedef vector<
        vector<int, int>,
        vector<int, int>,
        vector<int, int>> lotso;
    typedef mpl::transform<lotso,
        first_element<_1>>::type inst1;
    typedef first_element<
        at_c<lotso,0>>::type inst2;
    return 0;
}

我想您忘记了inst2的typedef中对at_c的调用后面有一个::type。回想一下,您的first_element期望可以应用at_c的内容。然而,尚未对原始at_c<lotso, 0>进行评估。通过添加::type来评估元函数。

#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/placeholders.hpp>
#include <type_traits>
using namespace boost;
using namespace boost::mpl;
template <typename VECTOR>
struct first_element : mpl::at_c<VECTOR, 0> {};
int main()
{
    typedef vector<
        vector<int, int>,
        vector<int, int>,
        vector<int, int>> lotso;
    typedef mpl::transform<lotso,
        first_element<_1>>::type inst1;
    typedef first_element<
        at_c<lotso,0>::type >::type inst2;
                     ^^^^^^ <--- you forgot a ::type here
    static_assert(std::is_same<first_element<inst1>::type, inst2>::value, "bingo");
    return 0;
}

实例。作为进一步的检查,我验证了对inst1的进一步取消引用给出了与inst2相同的类型。