关于模板别名

About template alias

本文关键字:别名 于模板      更新时间:2023-10-16

给定以下代码 2 个问题:

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>;
    
template <typename T> using RomoveRef = Fun<false>;
int main()
{
    RomoveRef<int&>::type j = 1; // ok
    printf("%dn", j);
    // question 2. I want to use Fun directly, how can i do?
    // template Fun<false>::type<int&> i = 1;
    // printf("%dn", i);
    return 0;
}

1.如何理解两种template <>立场?

2.如何使用Fun::typeFun_::type实现与RomoveRef相同的功能?

关于第一个问题,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>;