在C++11中增加的新特性,爲C++編程提供了極大的方便,可以用來替換的函數指針,當然,對比函數指針,std::function更加簡單,因爲它更像一個對象;
如下代碼顯示了幾種常用的形式,分別爲類普通成員函數,類靜態函數,普通靜態函數和普通函數,注意,在示例中普通靜態函數和普通函數的生存週期相同,可見範圍也是相同的,所以,並無太多差別(在該示例中)
#include <iostream>
#include <memory>
#include <functional>
static void printStatic()
{
std::cout << __FUNCTION__ << std::endl;
}
void printNormal()
{
std::cout << __FUNCTION__ << std::endl;
}
class testA
{
public:
typedef std::shared_ptr<testA> Ptr;
public:
testA()
{
std::cout << __FUNCTION__ << std::endl;
}
public:
void printPublic()
{
std::cout << __FUNCTION__ << std::endl;
}
static void printStatic()
{
std::cout << __FUNCTION__ << std::endl;
}
protected:
void printProtected()
{
std::cout << __FUNCTION__ << std::endl;
}
private:
void printPrivate()
{
std::cout << __FUNCTION__ << std::endl;
}
};
int main_test1()
{
testA test1;
auto bindFunc1 = std::bind(&testA::printPublic, test1);
bindFunc1();
// auto bindFunc2 = std::bind(&testA::printProtected, test1); // Error
// auto bindFunc3 = std::bind(&testA::printPrivate, test1); // Error
testA::Ptr test2(new testA);
auto bindFunc4 = std::bind(&testA::printPublic, test2);
// auto bindFunc5 = std::bind(&testA::printProtected, test2); // Error
// auto bindFunc6 = std::bind(&testA::printPrivate, test2); // Error
bindFunc4();
auto bindFunc7 = std::bind(testA::printStatic);
bindFunc7();
return 0;
}
int main_test2()
{
auto bindFunc1 = std::bind(printStatic);
bindFunc1();
auto bindFunc2 = std::bind(printNormal);
bindFunc2();
}
int main(int argc, char *argv[])
{
main_test1();
return 0;
}