首页 > 解决方案 > 如何编写将一种类型的指针/引用/限定符复制到另一种类型的元函数?

问题描述

我是 C++ 和模板的新手,想编写一个元函数,将一种类型的指针/引用/限定符复制到另一种类型(C++17/20)。

例如,some_func<const A*, A, B>生成const B*some_func<A*&&, A, B>生成B*&&some_fun无论*/&/const提供多少都应该是有效的。

标签: c++templatesc++17traits

解决方案


您可以使用模板部分专业化来做到这一点。

template <typename X, typename Y>
struct some_func {
    using type = Y;
};

template <typename X, typename Y>
struct some_func<const X*, Y> {
    using type = const Y*;
};

template <typename X, typename Y>
struct some_func<X*&&, Y> { 
    using type = Y*&&;
};

// ...

template <typename X, typename Y>
using some_func_t = some_func<X, Y>::type;

static_assert(std::is_same_v<some_func_t<const int *, float>, const float*>);
static_assert(std::is_same_v<some_func_t<int*&&, float>, float*&&>);

推荐阅读