如何将带有默认参数的模板函数传递给std :: call_once [英] How to pass template function with default arguments to std::call_once
问题描述
我需要在我的模板化单例类中使用std :: call_once,但是当前下面的示例代码无法编译:
I need to use std::call_once in my templatized singleton class but currently below sample code is not compiling :
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>
class Singleton
{
public:
inline static T* getInstance()
{
static std::unique_ptr<T> ptr(new T());
std::call_once(flag,&LifeTrackerHelper::SetLongevity<T>,ptr);
//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();
}
因此需要帮助以了解如何正确使用std :: call_once.
So need help in understanding how to properly use std::call_once here.
推荐答案
您的问题是&LifeTrackerHelper::SetLongevity<T>
是一个期望unique_ptr
和unsigned int
的函数指针,但它仅获得一个参数.尽管实际函数的第二个参数具有默认值,但在由函数指针调用时,它需要两个参数.
Your problem is &LifeTrackerHelper::SetLongevity<T>
is a function pointer expecting a unique_ptr
and an unsigned int
, but it only gets the one argument. While the actual function has a default value for the second argument, it needs both arguments when called by a function pointer.
您可以通过传递另一个参数来解决它:
You can fix it by passing another argument:
std::call_once(flag, &LifeTrackerHelper::SetLongevity<T>, ptr, 0);
或者您也可以将其包装在lambda中:
Or you can wrap it in a lambda:
std::call_once(flag, [](std::unique_ptr<T>& p){ return LifeTrackerHelper::SetLongevity<T>(p); }, ptr);
根据 cppreference ,在C ++ 17之前,call_once
将被复制或移动.到目前为止,通过unique_ptr
并没有出现任何错误,但是在其上使用std::ref
可能是明智的选择.
According to cppreference, before C++17 the arguments to call_once
will be copied or moved. So far, I haven't gotten any errors passing a unique_ptr
, but it might be wise to use std::ref
on it.
这篇关于如何将带有默认参数的模板函数传递给std :: call_once的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!