c++ - 关于别名模板

标签 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.如何理解两个模板<>的位置。 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>;

关于c++ - 关于别名模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008920/

相关文章:

c++ - SDL_WINDOWEVENT_SIZE_CHANGED 拖动边框调整大小时不出现?

c++ - 如何推断嵌套容器值类型

c++ - 复制原始类型行为的 std::vector

c++ - 安全地迭代 std::vector 而项目可能被删除

C++使用 header 定义的模板类乘以定义的符号

c++ - 使用模板时,constexpr 函数不是 constexpr

C++:获取参数包的头部和尾部

c++ - operator->返回的指针的有效性

c++ - 我如何一次完全生成一个随机数?

python - Swig Python 模块中的 C++ 内存泄漏