使用mpl::if_和integer模板参数选择类型

Selecting type with mpl::if_ and integer template parameter

本文关键字:参数 选择 类型 mpl if 使用 integer      更新时间:2023-10-16

以下代码适用于Visual Studio 2005,但使用g++4.4.5编译时会出现编译器错误:

#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>
template<int X> struct A
{
    void f() {
        typedef boost::mpl::if_<boost::mpl::bool_<X == 1>, int, bool>::type Type;
    }
};

这是我得到的错误:

main.cpp: In member function ‘void A<X>::f()’:
main.cpp:12: error: too few template-parameter-lists

代码出了什么问题?如果我用硬编码的数字替换模板化的X,代码编译得很好。我还尝试过用mpl::int_类型包装X,但没有成功。

谢谢!

您需要typename关键字:

typedef typename                   // <-- Here
    boost::mpl::if_<
        boost::mpl::bool_<X == 1>,
        int,
        bool
    >::type Type;

编译器无法确定mpl::if_<...>::type是一个类型,因为它不知道X的值:if_可能专门用于某些参数,并包括一个不是类型的type成员,例如:

//Silly if_ specialization
template <typename Then, typename Else>
struct if_<void, Then, Else>
{
    int type;
};

因此,您需要明确地告诉编译器::type表示一个类型,并使用typename关键字。

请参阅此处的深入解释:我必须将模板和typename关键字放在哪里以及为什么要放。