【发布时间】:2017-05-17 07:45:31
【问题描述】:
除了这个问题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 中使用重载函数时有任何特殊规则
【问题讨论】:
-
为什么不简单地使用 lambda 作为
std::call_once参数? -
std::call_once(flag,[&ptr]{LifeTrackerHelper::SetLongevity(ptr, 0);});
标签: c++ multithreading c++11 c++14