【问题标题】:Template default to a template with more templates模板默认为具有更多模板的模板
【发布时间】:2017-11-06 06:04:47
【问题描述】:

我正在尝试创建一个具有基于另一个模板的模板返回类型的函数,我也想将其默认为默认值。很难解释,但这里是代码:

template<template<typename ReturnType = float, typename> DurationType = std::chrono::duration<ReturnType, std::milli> >
ReturnType tick()
{
    high_resolution_clock::time_point currentPoint = high_resolution_clock::now();
    DurationType elapsed = currentPoint - mStartTimePoint;
    mStartTimePoint = currentPoint;

    return elapsed.count();
}

显然上面没有编译,但我想做的是让函数返回ReturnTypefloatdouble 可能)并指定返回类型的单位。在这种情况下,我希望它默认为毫秒。这可能吗?

【问题讨论】:

  • 你想在这里实现什么还不清楚。为什么将DurationType 提升为函数的模板参数,而它甚至没有出现在它的界面中?您可以将ReturnType 作为您唯一的模板参数,并将DurationType 替换为auto

标签: c++ c++11 templates chrono


【解决方案1】:

我不清楚你想要表达什么以及你想要默认什么。

例如,您可以定义一个模板ReturnT 类型,具有默认值,并表达一个DurationT 类型,其默认值依赖于ReturnT;像

template <typename ReturnT = float, 
          typename DurationT = std::chrono::duration<ReturnT, std::milli>>
ReturnT tick0 ()
 {
   std::chrono::high_resolution_clock::time_point
      currentPoint { std::chrono::high_resolution_clock::now() };

   DurationT elapsed { currentPoint } ;

   return elapsed.count();
 }

但是可以接受的是,使用DurationT 调用此函数,其返回类型不同于ReturnT

我的意思是:下面的调用是否可以接受?

foo0<long double, std::chrono::duration<float, std::milli>>();

我想不是。

所以我认为你应该只表达一种类型并派生另一种类型。

你可以表达DurationT,默认std::chrono::duration&lt;float, std::milli&gt;,推导出ReturnT;举例

template <typename DurationT = std::chrono::duration<float, std::milli>>
decltype( std::declval<DurationT>().count() ) tick1 ()
 {
   std::chrono::high_resolution_clock::time_point
      currentPoint { std::chrono::high_resolution_clock::now() };

   DurationT elapsed { currentPoint } ;

   return elapsed.count();
 }

或者你可以表达ReturnT,默认float,并从中推导出DurationT;举例

template <typename ReturnT = float>
ReturnT tick2 ()
 {
   using DurationT = std::chrono::duration<ReturnT, std::milli>;

   std::chrono::high_resolution_clock::time_point
      currentPoint { std::chrono::high_resolution_clock::now() };

   DurationT elapsed { currentPoint } ;

   return elapsed.count();
 }

【讨论】:

  • 我一直在想我需要使用模板模板...因为我的模板中有另一个模板。
  • @ChaoSXDemon - 在某些情况下有用;但我不认为在这种情况下。
猜你喜欢
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 2011-10-26
相关资源
最近更新 更多