C++模板元编程习题

2-0

编写一个一元元函数 add_const_ref<T>, 如果T是一个引用类型,就返回T,否则返回T const&。

#include <iostream>

template <bool b, typename T>
struct add_const_reference;

template <typename T>
struct add_const_ref
{
    using type = typename add_const_reference<std::is_reference<T>::value, T>::type;
};

template <typename T>
struct add_const_reference<false, T>
{
    using type = typename std::add_lvalue_reference<typename std::add_const<T>::type>::type;
};

template <typename T>
struct add_const_reference<true, T>
{
    using type = typename std::remove_reference<T>::type;
};

int main(int argc, char *argv[])
{
    using a = int&;
    using b = int;
    
    std::cout << std::is_same<b, typename add_const_ref<a>::type>::value << std::endl;
    
    using c = int const&;
    
    std::cout << std::is_same<c, typename add_const_ref<b>::type>::value << std::endl;
}

2-1

编写一个三元元函数 replace_type<c, x, y>, 让他接受一个任意的复合类型c作为其第一个参数,并将c中出现的所有type x替换为y;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容