【问题标题】:How to use overloaded function with std::call_once如何在 std::call_once 中使用重载函数
【发布时间】: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,[&amp;ptr]{LifeTrackerHelper::SetLongevity(ptr, 0);});

标签: c++ multithreading c++11 c++14


【解决方案1】:

您可以使用static_cast&lt;&gt;() 指定您所指的重载。例如,

 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);

【讨论】:

  • 这看起来很不愉快,没有更好的方法
  • 是的,到目前为止我只使用这种方法,但只是想知道是否可以仅使用函数指针来做更好的事情
猜你喜欢
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
相关资源
最近更新 更多