![](/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.