注意:这篇文章上次更新于842天前,文章内容可能已经过时。
分享一个在公司看到的头文件。
#include <functional>
#include <cstddef>
// 禁止拷贝构造函数
class disable_copying
{
public:
disable_copying(){}
virtual ~disable_copying(){}
private:
disable_copying& disable_copying(const disable_copying&) = delete;
disable_copying& disable_copying(disable_copying&&) = delete;
};
// 禁止赋值构造函数
class disable_assignment
{
public:
disable_assignment(){}
virtual ~disable_assignment(){}
private:
disable_assignment& operator=(const disable_assignment&) = delete;
disable_assignment& operator=(disable_assignment&&) = delete;
};
// 禁止拷贝和赋值构造函数
class disable_copying_and_assignment:public disable_copying , public disable_assignment
{
public:
disable_copying_and_assignment(){}
virtual ~disable_copying_and_assignment(){}
};
// 作用域智能函数
template<class Fn> class smart_function : public disable_copying_and_assignment
{
public:
smart_function(Fn release):release_(release)
{
}
explicit smart_function(Fn&& release):release_(release)
{
}
virtual ~smart_function() override
{
if(release_ != nullptr)
{
release_();
}
}
private:
Fn release_;
};
// 双智能函数
template<class Fn1, class Fn2>
class smart_both_function:public disable_copying_and_assignment
{
public:
smart_both_function(Fn1 initialize,Fn2 release):release_(release)
{
if(initialize != nullptr){
initialize();
}
}
explicit smart_both_function(Fn1&& initialize,Fn2&& release):release_(release)
{
if(initialize != nullptr)
{
initialize();
}
}
virtual ~smart_both_function() override
{
if(release_ != nullptr)
{
release_();
}
}
private:
Fn2 release_;
};
// 智能条件函数
template<class Fn1, class Fn2>
class smart_condition_function:public disable_copying_and_assignment
{
public:
smart_condition_function(Fn1 condition,Fn2 release)
:condition_(condition),release_(release)
{
}
explicit smart_condition_function(Fn1&& condition,Fn2 release)
:condition_(condition),release_(release)
{
}
virtual ~smart_condition_function() override
{
if(condition_ && condition_() && release_)
{
release_;
}
}
private:
Fn1 condition_;
Fn2 release_;
};
using smart_lambda = smart_function<std::function<void()>>;
using smart_both_lambda = smart_both_function<std::function<void()>,std::function<void()>>;
using smart_condition_lambda = smart_condition_function<std::function<void()>,std::function<void()>>;
使用方法:
- 如果你想写一个删除掉拷贝构造函数和拷贝赋值函数的类,那么你可以继承 disable_copying_and_assignment
class myclass : public disable_copying_and_assignment
{
};
- smart_lambda 有点类似于 lock_guard ,在离开作用域时执行函数。一个可能的使用场景是当你的函数中存在许多分支,但是return之前必须做一件相同的事,使用 smart_lambda 可以避免代码的重复。
void function(int index)
{
smart_lambda sl([](){std::cout << "函数执行结束了!";});
switch(index)
{
case 0:
{
std::cout<< 0 << endl;
return;
}
case 1:
{
std::cout << 1 << endl;
return;
}
default:
{
return;
}
}
return;
}
这样无论从哪个分支结束,都会输出函数执行结束了。
smart_both_lambda 和 smart_condition_lambda 的功能也显而易见。