当前位置: 首页 > 知识库问答 >
问题:

用户定义转换中的模板参数类型推导

冯卓
2023-03-14

我正在尝试创建一个结构超时。我想直接使用它。e、 g.std::此线程::睡眠(超时)。但是,当从struct timeout转换为std::chrono::duration时,我的用户定义转换失败

#include <chrono>
#include <thread>
template <typename Duration = std::chrono::milliseconds>
struct timeout_tp
{
   using Duration_   = Duration;
   using rep_        = typename Duration_::rep;
   using period_     = typename Duration_::period;

   timeout_tp(const rep_ &timeout) : timeout{timeout} {}    
   operator Duration_() const {return timeout;}
   Duration_ operator()() const {return timeout;}
   //...
   private:   
   Duration_ timeout;
};

int main()
{
   timeout_tp<std::chrono::seconds> timeout{1};
   std::chrono::seconds x = timeout; //OK: struct timeout conversion to std::chrono::seconds.
   std::this_thread::sleep_for(x);
   //std::this_thread::sleep_for(timeout); : FAILS!!! Can't understand why... 
   std::this_thread::sleep_for(timeout()); //OK : struct timeout operator() returns std::chrono::seconds.
   return 0;
}

我做错了什么?

我需要做什么才能使用所需的语法?

编译器发出的错误消息:

main.cpp:38: 39:错误:没有匹配函数调用'sleep_for(timeout_tp

在文件包括从main.cpp:16: 0: /usr/include/c /7/thread: 361:7:注意:候选人:模板无效STd::this_thread::sleep_for(constd::chrono::d

main.cpp:38: 39:注:'timeout_tp


共有1个答案

郏志学
2023-03-14

::std::this_thread::sleep_for是声明为

template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period> & sleep_duration );

当您传递一个timeout\u tp实例时,无法推导模板参数RepPeriod,甚至不考虑用户定义的转换运算符timeout\u tpstd::chrono::microsides

 类似资料:
  • 我可以看到,当我逐步通过代码,C样式的强制转换直接到参数包构造函数。为什么这是,我做错了什么?如何防止参数包构造函数似乎隐藏用户定义的转换?

  • 问题内容: 就像我们使用__ToString一样,有没有一种方法来定义铸造方法? 问题答案: 无需在php中键入强制类型转换。 编辑: 由于这个话题似乎引起一些混乱,我想我要详细说明一下。 在Java之类的语言中,有两种可能带有类型。编译器有一个关于类型的概念,而运行时还有一个关于类型的想法。编译器的类型与变量相关,而运行时引擎则跟踪值的类型(已将其分配给变量)。变量类型在编译时是已知的,而值类型

  • 考虑以下类。如何在不使用自定义转换器的情况下使用Dozer将A类转换为B类? 有人能为上述类提供推土机映射XML吗?

  • 使用以下代码生成时 生成以下诊断(代码后): 诊断: 有趣的部分不是关于歧义错误本身(这不是这里主要关注的问题)。有趣的是,当仅使用函数名调用fun时,第一个fun的模板参数F被解析为纯函数类型double(double),而第二个fun的模板参数F被解析为更期望的函数指针类型。 然而,当我们将调用<代码>乐趣(测试) 更改为<代码>乐趣( 这种行为似乎是所有Clang和GCC(以及Visual

  • 考虑以下示例: 而且,如果我们将非类型模板参数的类型改为占位符类型,如下所示: 然后,GCC接受,而Clang拒绝它(两者都拒绝,如上)。 海合会演示,铿锵演示。 (1)GCC HEAD 11.0.0 202 10117和Clang HEAD 12.0.0(20210118),。

  • 另一个有用的可能示例:(伪代码)