gpt4 book ai didi

c++ - 如何通过 std::call_once 使用重载函数

转载 作者:行者123 更新时间:2023-11-30 03:31:41 24 4
gpt4 key购买 nike

除了这个问题How to pass template function with default arguments to 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);

关于c++ - 如何通过 std::call_once 使用重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44018604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com