使用mpl::if_和integer模板参数选择类型
Selecting type with mpl::if_ and integer template parameter
以下代码适用于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关键字放在哪里以及为什么要放。
相关文章:
- 如何使用默认参数等选择模板专业化
- 对可变参数使用声明.如何选择正确的功能
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 使模板函数按函数参数选择类型
- 根据模板参数选择宏定义
- 使用 std::条件根据模板参数选择成员类型
- 根据 C++11 中的模板参数选择数组大小
- 为什么 lambda 自动和参数选择常量重载?
- 如何使用模板参数选择方法调用
- 如何根据参数选择变量
- 根据函数参数选择派生类
- 如何根据模板参数选择替代成员函数实现
- 使用mpl::if_和integer模板参数选择类型
- 根据模板参数选择合适的复制构造函数
- 参数选择的问题
- 通过模板参数选择子类与实例化成员变量的区别
- 根据模板整数参数选择一个整数类型
- 根据模板参数选择枚举类型
- 根据模板参数选择函数名称
- 根据模板参数选择联合成员