右值引用
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表达式子是仿函数
模板
- 模板显式实例化
template <typename T>
void fun(T arg){}
template void fun(int)
- 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;
}