CTAD(类模板实参推导)、推导指引、enable_if_t、is_same、requires

c++17引入了类模板参数推断

template<typename T>
class Test
{
public:
    Test(T tt):t(tt){cout<<typeid(t).name()<<endl;};
private:
    T t;
};
//推导指引
// Test(const char*)->Test<string>;
int main()
{
    Test t1(1.2);//T类型为double
    Test t2("123");//未使用推导指引时,类型为PKc,表示pointer(P) const(K) char(c),即const char*
    return 0;
}

SFINAE:匹配失败不是错误

SFINAE特性会引导编译器在遭遇特化失败后放弃该模板并转向其他函数,且不会报错

  • enable_if_t的使用

    //两种写法是一样的
    template<typename T>
    std::enable_if_t<std::is_integral_v<T>, float> fun2(T x) {
        std::cout << "floating point type" << std::endl;
        return x;
    }
    
    template<typename U> 
    std::enable_if_t<std::is_same_v<U, int>, float> fun(U b){
        std::cout<<typeid(b).name()<<std::endl;
        return 3.5;
    }
    

    enable_if_t<is_same_v<T, 参数类型>, 返回值类型> fun(T t)

    • 练习
      使用enable_if_t使得参数匹配到string fun()
      #include <vector>
      #include <iostream>
      #include <numeric>
      using namespace std;
      
      template<class T>
      enable_if_t<!is_same_v<T, const char *>, T> fun(T t)
      {
          return t*2;
      }
      string fun(string s)
      {
          return s + s;
      }
      int main()
      {
          cout<<fun(2)<<endl;
          cout<<fun(string("nh"))<<endl;//这里不会自动将const char * 转为string,使用enable_if_t解决
          return 0;
      }
      

sizeof…

用于计算参数包的元素个数

template<class... T>
//当且仅当所有T类型都是double,整个条件类型才为真,函数返回值才是int
enable_if_t<(is_same_v<T, double>&& ...), double> test(T... a)
{
    cout<<sizeof...(T)<<endl;
}

is_same<A,B>::value返回 类型A和类型B 是否相同,等价于is_same_v<A,B>

template<class T>
bool test2(T a)
{
    if (is_same<T,int>::value)
    {
        cout<<"int"<<endl;
    }
    else if(is_same<T, double>::value)
    {
        cout<<"double"<<endl;
    }
    else
    {
        cout<<"xx"<<endl;
    }
}

细节1:为了避免报错,需要编译期就不编译到return t+1,因此下面使用constexpr

#include <iostream>
#include <type_traits>
#include <string>

template<class T>
auto fun(T t)
{
    if constexpr (std::is_same_v<T, int>)
    {
        return t + 1;
    }
    else
    {
        return t.substr(1);//ello
    }
}
int main() {
    std::string s = "hello";
    std::cout<< fun(s);
    return 0;
}

细节2:decltype推导类型会推导出&和const,因此下面这样写无论如何都是进else分支,导致报错
解决方法:使用std::decay_t:会去掉& && const,数组也会退化成指针。即std::is_same_v<std::decay_t<decltype(t)>, int>)std::decay(xx,yy)::type等价于std::decay_t(xx,yy)
**更隐蔽的易错点:**如果是想判断数组的元素是不是int,也需要使用std::decay_t。因为t[0]等价于t.operator,其返回的是引用类型,即int&

auto fun(T const &t)
{
    if constexpr (std::is_same_v<decltype(t), int>)
    {
        return t + 1;
    }
    else
    {
        return t.substr(1);
    } 
}

获取容器类型的方式:tyepname T::value_type
当使用xx::type或decay<xx>::type且xx含有模板时,就使用typename

#include <iostream>
#include <vector>
#include <type_traits>
#include <string>
template<class T>
auto fun(T t)
{
    if constexpr (std::is_same_v<typename T::value_type, int>)
    {
        return t[0] + 1;
    }
    else
    {
        return t[0].substr(1);
    }
}
int main() {
    std::vector<int> s={5};
    std::cout<< fun(s)<<std::endl;
    return 0;
}

一些简化写法:

std::is_void_v<xx>等价于std::is_same_v<xx, void>
同理还有,is_null_pointer_v、is_integral_v、is_lvalue_reference_v、is_const_v等等

c++20的requires:对函数模板、类模块成员函数 的参数进行约束,为真才能使用该模板。如下示例不会报错。

#include <iostream>
#include <vector>
#include <type_traits>
#include <string>

template<class T>
void fun(T t)
{
    std::cout<<"函数1 "<<t<<std::endl;
}

template<class T>
    requires(std::is_integral_v<std::invoke_result_t<T>>)
void fun(T t)
{
    std::cout<<"函数2 "<<t<<std::endl;
}

int main() {
    fun("a");
    fun(3);
    return 0;
}

非c++20里,要想实现上述功能,可以使用SFINAE思想

template <class T, std::enable_if_t<std::is_void_v<T>, int> = 0>
void fun(T t)
{
    std::cout<<"函数1 "<<t<<std::endl;
}

template <class T, std::enable_if_t<!std::is_void_v<T>, int> = 0>
void fun(T t)
{
    std::cout<<"函数2 "<<t<<std::endl;
}

判断对象具有某函数

c++20中使用requires判断命令是否能成功运行

#include <iostream>
#include <type_traits>

struct A
{
    void fun1()
    {
        std::cout<<"fun1"<<std::endl;
    }
};
struct B
{
    void fun2()
    {
        std::cout<<"fun2"<<std::endl;
    }
};

//如果对象有fun1函数,就调用fun1,否则调用fun2
template <class T>
void gench(T t)
{
    if constexpr (requires{t.fun1();})
    {
        t.fun1();
    }else
    {
        t.fun2();
    }
}
 
int main() {
    A a;
    B b;
    gench(a);
    gench(b);

    return 0;
}

非c++20中,不能使用requires来判断,可以专门写一个类模板来指明是否有fun1函数

#include <iostream>
#include <type_traits>

struct A
{
    void fun1()
    {
        std::cout<<"fun1"<<std::endl;
    }
};
struct B
{
    void fun2()
    {
        std::cout<<"fun2"<<std::endl;
    }
};

//主模板
template<class T>
struct has_fun1
{
    static constexpr bool value = false;
};
//特化
template<>
struct has_fun1<A>
{
    static constexpr bool value = true;
};


//如果对象有fun1函数,就调用fun1,否则调用fun2
template <class T>
void gench(T t)
{
    if constexpr (has_fun1<T>::value)
    {
        t.fun1();
    }else
    {
        t.fun2();
    }
}

int main() {
    A a;
    B b;
    gench(a);
    gench(b);

    return 0;
}

type_traits

#include <iostream>
#include <type_traits>

//1.参数类型的判断
template<class T>
std::enable_if_t<std::is_integral<T>::value, int> fun(T t){
    std::cout<<"T是int型,那么这里就返回int型"<<std::endl;
}

template<class T>
std::enable_if_t<std::is_same<T, float>::value, float> fun(T t){
    std::cout<<"T是float型,那么这里就返回float型"<<std::endl;
}

//2.去掉const的办法
template<class T>
struct remove_const{
    using type = T;
};

template<class T>
struct remove_const<const T>{
    using type = T;
};

//3.实现std::is_same<T,float>::value这样的功能
//先定义好true和false
struct true_type{
    static constexpr bool value = true;
};
struct false_type{
    static constexpr bool value = false;
};

template<class, class>
struct my_is_same : false_type{};

template<class T>
struct my_is_same<T, T> : true_type{};

//4.判断继承关系:type_trait中是std::is_base_of<Animal, Cat>::value
class Animal{
};
class Cat:public Animal{
};


int main(){
    float a = 2.5;
    fun(a);

    const char* s = "xx";

    std::cout<<"自己实现的is_same:"<<my_is_same<int,int>::value<<std::endl;

    std::cout<<std::is_base_of<Animal, Cat>::value<<std::endl;//1

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值