再学C++

右值引用

struct Base
{
    Base()
    { _dat=0;   }
    Base(Base&& other)//移动构造
    {
        _dat=other._dat;
    }
    int _dat;
};
class Obj:public Base
{
public:
    Obj(){}
    Obj(Obj&& other):Base(std::move(other)){}//调用父类的移动构造

};
    Obj Obj1;
    Obj1._dat=1;
    Obj Obj2(std::move(Obj1));

完美转发

引用折叠

//重载被调用函数,查看完美转发的效果
void otherdef(int & t) {
    cout << "lvalue\n";
}
void otherdef(const int & t) {
    cout << "rvalue\n";
}
/**
被完美转发替代
//重载函数模板,分别接收左值和右值
//接收右值参数
//template <typename T>
//void function(const T& t) {
//    otherdef(t);
//}
//接收左值参数
//template <typename T>
//void function(T& t) {
//    otherdef(t);
//}
**/
template <typename T>
void foo(T&& arg)
{
   otherdef(std::forward<T>(arg));
}
    foo(5);
    int a=5;
    foo(a);

可变参模板

void fun()
{

}
template <typename T,typename... Args>
void fun(T firstArg,Args... args)
{
    //deal firstArg
    
    fun(args...);
}

仿函数

重载类的()运算符

struct A
{
	A(int _a):
	double opetator()(double a)
	{
			return a*a;
	}
	double _a;
}

A(10.)(100);
std::vector<double> data={1,2,3,4};
std::transform(data.begin(),data.end(),A(10.));

lambda表达式子是仿函数

模板

  1. 模板显式实例化
template <typename T>
void fun(T arg){}
template void fun(int)
  1. static_assert

模板特化

https://blog.csdn.net/K346K346/article/details/82179205

enum TType
{
    One,
    Two
};
template <TType type,typename T>
struct A
{
    void operator()(T t)
    {}
};
template <typename T>
struct A<TType::One, T>
{
    void operator()(T t)
    {

    }
};
template <typename T>
struct A<TType::Two, T>
{
    void operator()(T t)
    {

    }
};
A<TType::One,int>()(12);
A<TType::Two,int>()(12);

SFINAE

Substitution failure is not an error
在编译时期来确定某个 type 是否具有我们需要的性质,故意让某个模板匹配失败来匹配其他模板。

//template <typename T>
//decltype (T().size(),typename T::size())len(const T& t)
//{
//    return  t.size();
//}

template <typename T>
decltype (T().size(),typename T::size_type()) len( T const & t)//T().size()判断类型存在size()
{
    return  t.size();
}
unsigned len(...)
{
    return  0;
}
class A
{
public:
    using size_type=size_t;
};

enable_if

通用模板+特化

 // Primary template.
  /// Define a member typedef @c type only if a boolean constant is true.
  template<bool, typename _Tp = void>
    struct enable_if
    { };

  // Partial specialization for true.
  template<typename _Tp>
    struct enable_if<true, _Tp>
    { typedef _Tp type; };
//下面二者相等,因为enable_if有个默认模板参数void
template<typename  T, typename std::enable_if<std::is_same<T, int>::value, int>::type = 0>
T foo() {
    return 42;
}
template<typename  T, typename std::enable_if<std::is_same<T, int>::value>::type* = nullptr>
T foo() {
    return 42;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值