![](/img/trans.png)
[英]How to pass template function with default arguments to std::call_once
[英]How to use overloaded function with std::call_once
除了这个问题之外, 如何将带有默认参数的模板函数传递给std :: call_once ,通过使用函数指针时甚至通过传递默认参数来解决,但是现在当我在实际代码中尝试此解决方案时,我发现它不起作用,因为存在一个重载函数也:
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 :: call_once中使用重载函数时,有任何特殊规则
您可以使用static_cast<>()
指定要表示的重载。 例如,
std::call_once(flag,
static_cast<int (*)(std::unique_ptr<T>&, unsigned int)>(
&LifeTrackerHelper::SetLongevity<T>),
std::ref(ptr), 0);
您也可以使用临时变量来达到相同的效果。
int (*initfn)(std::unique_ptr<T>&, unsigned int) =
&LifeTrackerHelper::SetLongevity<T>;
std::call_once(flag, initfn, std::ref(ptr), 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.