如何同时对模板函数进行别名和实例化?
How to alias and instantiate a template function at same time?
我有一个模板函数如下:
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 就好像它是一个普通函数而不是一个模板。
谢谢!
您可以获得指向所需函数的函数指针,然后将其用作您的 "alias"。看起来像:
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);
};
我有一个模板函数如下:
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 就好像它是一个普通函数而不是一个模板。 谢谢!
您可以获得指向所需函数的函数指针,然后将其用作您的 "alias"。看起来像:
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);
};