C++ 如何将重载函数与std::call_一起使用一次
除了在使用函数指针时通过传递默认参数解决的问题之外,现在当我在实际代码中尝试此解决方案时,我发现它不起作用,因为还有一个重载函数:C++ 如何将重载函数与std::call_一起使用一次,c++,multithreading,c++11,c++14,C++,Multithreading,C++11,C++14,除了在使用函数指针时通过传递默认参数解决的问题之外,现在当我在实际代码中尝试此解决方案时,我发现它不起作用,因为还有一个重载函数: std::once_flag flag; class LifeTrackerHelper { public: template<class T> inline static int SetLongevity(std::unique_ptr<T>& pobj,unsigned int longevity = 0) { retur
std::once_flag flag;
class LifeTrackerHelper
{
public:
template<class T>
inline static int SetLongevity(std::unique_ptr<T>& pobj,unsigned int longevity = 0)
{
return 0;
}
template<class T>
inline static int SetLongevity(unsigned int longevity = 0)
{
return 0;
}
};
template<class T>
class Singleton
{
public:
inline static T* getInstance()
{
static std::unique_ptr<T> ptr(new T());
std::call_once(flag,&LifeTrackerHelper::SetLongevity<T>,std::ref(ptr),0);
//static int i = LifeTrackerHelper::SetLongevity<T>(ptr);
// if call_once is commented and above line uncommented this will work
return ptr.get();
}
};
class Test
{
public:
void fun()
{
std::cout<<"Having fun...."<<std::endl;
}
};
;
int main()
{
Singleton<Test>::getInstance()->fun();
return 0;
}
std::once_标志;
类LifeTrackerHelper
{
公众:
模板
内联静态整数设置寿命(std::unique_ptr&pobj,无符号整数寿命=0)
{
返回0;
}
模板
内联静态整数设置寿命(无符号整数寿命=0)
{
返回0;
}
};
模板
单件阶级
{
公众:
内联静态T*getInstance()
{
静态std::unique_ptr ptr(新的T());
std::call_once(flag,&LifeTrackerHelper::setLonelopy,std::ref(ptr),0);
//静态int i=LifeTrackerHelper::设置寿命(ptr);
//如果call_once被注释,且行上方未注释,则此操作将有效
返回ptr.get();
}
};
课堂测试
{
公众:
虚无乐趣()
{
std::cout您可以使用static\u cast()
指定您所指的重载。例如
std::call_once(flag,
static_cast<int (*)(std::unique_ptr<T>&, unsigned int)>(
&LifeTrackerHelper::SetLongevity<T>),
std::ref(ptr), 0);
std::调用_一次(标志,
静态浇铸(
&LifeTrackerHelper::设置寿命),
标准::参考(ptr),0);
也可以使用临时变量实现相同的效果
int (*initfn)(std::unique_ptr<T>&, unsigned int) =
&LifeTrackerHelper::SetLongevity<T>;
std::call_once(flag, initfn, std::ref(ptr), 0);
int(*initfn)(std::unique_ptr&,unsigned int)=
&LifeTrackerHelper::设置寿命;
std::call_一次(flag,initfn,std::ref(ptr),0);
为什么不直接使用lambda作为std::call_once
参数?std::call_once(flag,[&ptr]{LifeTrackerHelper::setLonelopy(ptr,0);})
这看起来很不愉快没有更好的方法是的,目前我只使用这种方法,但只是想知道是否可以只使用函数指针来做更好的事情