C++ 元函数的学习一

简介

参考书籍
C++模板元编程实战 -- 李伟
感觉这本书很超值,因为 zsvh 知乎大佬都给写题序了

简单code

header

#include <iostream>
// 顺序结构
template <typename T>
struct RemoveReferenceConst_ {
private:
    using inter_type = typename std::remove_reference<T>::type;
public:
    using type = typename std::remove_const<inter_type>::type;
};

template <typename T>
 using RemoveReferenceConst = typename RemoveReferenceConst_<T>::type;

// 分支结构
namespace tt{
template <bool B, typename T, typename F>
    struct conditional {
        using type = T;
    };

template <typename T, typename F>
    struct conditional<false, T, F>{
        using type = F;
    };

template <bool B, typename T, typename F>
using conditional_t = typename conditional<B, T, F>::type;
}


// 分支结构2 部分特化
struct A; struct B;
template <typename T>
struct Fun_ {
    constexpr static size_t value = 0;
};

template<>
struct Fun_<A> {
    constexpr static size_t value = 1;
};

template<>
struct Fun_<B> {
    constexpr static size_t value = 2;
};

// 分支结构3 部分特化简化版本  C++14
template<typename T>
constexpr size_t Fun = 0;

template<>
constexpr size_t Fun<A> = 1;

template<>
constexpr size_t Fun<B> = 2;

/**
 * @description: 完全特例化 转为  部分特例化
 * @param {*}
 * @return {*}
 */
/*
 * template <typename TW>
 * struct Wrapper {
 *  template <typename T>
 *  struct Fun_ {
 *      constexpr static size_t value = 0;
 *  };
 *  template <>
 *  struct Fun_<int> {
 *      constexpr static size_t value = 1;
 *  };
 * };
 * 
*/

struct Wrapper {
template <typename T, typename TDummy = void>
struct Fun_ {
constexpr static size_t value = 0;
};
template <typename TDummy>
struct Fun_<int, TDummy> {
   constexpr static size_t value = 1;
};
};

// 分支结构实现结构3  利用这个结构实现同名函数返回值不同的操作
namespace ss{
    template <bool B, typename T = void>
    struct enable_if {};

    template <class T>
    struct enable_if<true, T> {using type = T; };

    template <bool B, class T = void>
    using enable_if_t = typename enable_if<B, T>::type;
}

template <bool IsFeedbackOut, typename T, ss::enable_if<IsFeedbackOut>* = nullptr>
auto FeedbackOut_(T&&){
    return 1;
}
template <bool IsFeedbackOut, typename T, ss::enable_if_t<!IsFeedbackOut>* = nullptr>
auto FeedbackOut_(T&&) {
    return 2.0f;
}
#include "header.hh"
using namespace std;
int main(){
RemoveReferenceConst<const int&> h = 3;
cout << h << endl;
tt::conditional<true, int, float>::type x = 3; // 不能用std 因为会和库里面的std冲突
tt::conditional_t<false, int, float> y = 1.0f;
cout << x << endl;
cout << y << endl; 
constexpr size_t h1 = Fun_<B>::value;
cout << h1 << endl;

constexpr size_t h2 = Fun<B>;
cout << h2 << endl;

FeedbackOut_<true, int>(2);
}

原文地址:https://www.cnblogs.com/eat-too-much/p/14316014.html