我有一个模板函数,如下所示。
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<microseconds>( 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,好像它是一个普通函数,而不是一个模板。
你可以得到一个指向你想要的函数的指针,然后用它作为你的 "别名"。 这样看起来就像。
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);
};