用于类型转换的元函数
Metafunction for type conversion
可能的重复项:
我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?
我正在通过"C++模板元编程:来自 Boost 和超越的概念、工具和技术"一书学习模板编程,不知何故,我让自己卡在了第一个练习中。
任务是编写一个一元元函数add_const_ref<T>
,如果它是引用类型,则返回 T
,否则返回 T const &
。
我的方法是:
template <typename T>
struct add_const_ref
{
typedef boost::conditional
<
boost::is_reference<T>::value, // check if reference
T, // return T if reference
boost::add_reference // return T const & otherwise
<
boost::add_const<T>::type
>::type
>::type
type;
};
我试图测试它(我正在使用谷歌单元测试框架,因此语法):
TEST(exercise, ShouldReturnTIfReference)
{
ASSERT_TRUE(boost::is_same
<
int &,
add_const_ref<int &>::type
>::value
);
}
但它不编译:
main.cpp:27:5: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct boost::add_reference’
main.cpp:27:5: error: expected a type, got ‘boost::add_const<T>::type’
main.cpp:28:4: error: template argument 3 is invalid
我真的不明白为什么boost::add_const<T>::type
不符合成为类型的要求。我希望得到一个提示,说明我做错了什么。
你在这里错过了很多typename
:
template <typename T>
struct add_const_ref
{
typedef typename boost::conditional
// ^^^^^^^^
<
boost::is_reference<T>::value, // check if reference
T, // return T if reference
typename boost::add_reference // return T const & otherwise
// ^^^^^^^^
<
typename boost::add_const<T>::type
// ^^^^^^^^
>::type
>::type
type;
};
相关文章:
- C++:用户定义的显式类型转换函数错误
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 如何在参数中定义隐式类型转换的构造函数?
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 从 cpp lib 调用函数时的数据类型转换
- 如何为具有常量类型的函数正确转换来自 DLsym 的返回值?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 指向类成员函数的指针中存在类型转换错误
- C++ 函数重载不明确,没有自动类型转换
- 具有重载类型转换运算符的函数对象崩溃
- 将函数指针类型转换为相应的字符串
- 类型转换运算符重载与 as 非成员函数
- 是否可以将一种函数类型转换为另一种采用相同参数但返回类型不同的函数类型
- 需要构造函数/析构函数/类型转换错误
- 错误:从"<未解析的重载函数类型>"转换为非标量类型
- 特征日志和exp函数类型转换错误
- 具有构造函数类型转换和转换操作符的转换序列