【问题标题】:How to alias and instantiate a template function at same time?如何同时别名和实例化模板函数?
【发布时间】:2020-05-26 13:35:07
【问题描述】:

我有一个模板函数如下:

using namespace std::chrono;
using namespace std::chrono_literals;
template <typename D>
time_point<system_clock, D> makeTime(
   int year, int month, int day, int hour = 0, int minute = 0,
   int second = 0, int ms = 0, int us = 0, int ns = 0 );

通常,我这样称呼它:auto us_tp1 = makeTime&lt;microseconds&gt;( 2020, 5, 26, 21, 21, 21, 999, 123 );

但现在我需要通过别名“makeTimeUS”在某处调用它,如下所示:

auto us_tp1 = makeTimeUS( 2020, 5, 26, 21, 21, 21, 999, 123 );

就像 makeTimeUS 是 makeTime 的一个实例一样。

我试过了:

using makeTimeUS = template time_point<system_clock, microseconds> makeTime;

还有这个:

using makeTimeUS = template time_point<system_clock, microseconds> makeTime(
 int, int, int, int, int, int, int, int, int );

但两者都无法通过编译。

如何实例化一个模板函数并同时为其赋予别名? 我需要这样做的原因是,调用 makeTimeUS 的旧代码太多,就好像它是普通函数而不是模板一样。 谢谢!

【问题讨论】:

    标签: c++ templates alias instantiation using


    【解决方案1】:

    您可以获得指向所需函数的函数指针,然后将其用作“别名”。看起来像:

    auto makeTimeUS = makeTime<microseconds>;
    

    并且可以像这样使用:

    auto us_tp1 = makeTimeUS( 2020, 5, 26, 21, 21, 21, 999, 123 );
    

    但这只是让您更改名称。由于它是一个函数指针,默认参数不再起作用,您仍然需要指定所有参数。

    要解决这个问题,您可以使用 lambda 制作包装器而不是别名,这看起来像

    auto makeTimeUS = [](int year, int month, int day, int hour = 0, 
                         int minute = 0, int second = 0, int ms = 0)
                      { 
                           return makeTime<microseconds>(year, month, day, hour, minute, second, ms); 
                      };
    

    【讨论】:

    • 感谢您的帮助!它可以工作,但每次调用它时,我都必须给出完整的参数,不能省略最后几个参数。
    • @Leon 如果你想要,那么你需要一个包装器,而不是别名。你可以使用像 auto makeTimeUS = [](int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int ms = 0){ return makeTime&lt;microseconds&gt;(year, month, day, hour, minute, second, ms); } 这样的 lambda
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多