关于别名模板

时间:2019-01-02 15:24:40

标签: c++ c++11 templates

template <bool AddOrRemoveRef>
struct Fun_;

template <>
struct Fun_<true> {
    template <typename T> using type = std::add_lvalue_reference<T>;
};

template <>
struct Fun_<false> {
   template <typename T> using type = std::remove_reference<T>;
};

template <typename T>
template<bool AddOrRemove>
using Fun = typename Fun_<AddOrRemove>:: template type<T>;

// question 1. I changed the two template <> postion,and got a compile error.So i really can not distinguish the sequence of two template <T> in this situation. Is there some introduction?
// template <bool AddOrRemove>
// template <typename T>
// using Fun = typename Fun_<AddOrRemove>:: template type<T>;

template <typename T> using RomoveRef = Fun<false>;

int main()
{
    RomoveRef<int&>::type j = 1; // ok
    printf("%d\n", j);

    // question 2. I want to use Fun directly, how can i do?
    // template Fun<false>::type<int&> i = 1;
    // printf("%d\n", i);

    return 0;
}

我在上面的代码的注释部分中写了两个问题。如果可能,请给我一些建议,谢谢。

1。如何理解两个 template <> 位置。 2.如何使用 Fun :: type Fun _ :: type 实现与 RomoveRef

相同的功能

1 个答案:

答案 0 :(得分:1)

关于第一个问题,g++说“参数列表太多”,clang++说“别名模板声明中的外部模板参数列表”。 为了使代码编译,您应该编写以下代码:

template <bool AddOrRemove, typename T>
using Fun = typename Fun_<AddOrRemove>::template type<T>;

关于第二个功能,如果我理解正确,也许你想要类似的东西

template <typename T>
using RomoveRef = Fun<!std::is_reference<T>::value, T>;
相关问题