用于类型转换的元函数

Metafunction for type conversion

本文关键字:函数 类型转换 用于      更新时间:2023-10-16

可能的重复项:
我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?

我正在通过"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;
};