【发布时间】:2012-05-07 14:19:25
【问题描述】:
可能重复:
Where and why do I have to put the “template” and “typename” keywords?
我正在通过《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;
};
我尝试对其进行测试(我使用的是 Google 单元测试框架,因此使用了语法):
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 不符合成为类型的要求。我会很感激提示我做错了什么。
【问题讨论】:
标签: c++ templates metaprogramming boost-mpl