您可以使用 typedef 为类型创建更短更简单的名称:
typedef std::chrono::high_resolution_clock Clock;
typedef Clock::time_point TimePoint;
typedef std::chrono::seconds Seconds;
typedef std::chrono::milliseconds Milliseconds;
以及实例化的模板类型:
typedef std::chrono::duration<float, std::ratio<1>> RealDuration;
// Example usage
float dt = RealDuration(a - b).count();
对于函数指针:
typedef void (*FuncPtr)(int,int);
您还可以为模板使用类型别名:
template<typename T> using uptr = std::unique_ptr<T>;
// Example usage
uptr<int> myInt;
uptr<foo> myFoo;
但是如何创建一个指向模板函数的别名/指针呢?例如,如果我希望能够使用名称 DurationCast 来编写如下内容:
x = DurationCast<Seconds>(a - b);
y = DurationCast<Milliseconds>(c - d);
缩短函数需要做些什么std::chrono::duration_cast<T>()
只需 DurationCast<T>()
没有简单地去using namespace std::chrono;
或 using std::chrono::duration_cast;
路由,而且不用自己写函数对象来实现吗?
编辑: 我想我可以围绕它写一个简单的包装器:
template<typename ToType, typename FromType>
ToType DurationCast(const FromType& d)
{
return std::chrono::duration_cast<ToType>(d);
}
不像别名那样工作,但最终结果是我可以以与我的目标完全相同的方式使用它:
x = DurationCast<Seconds>(a - b);
最佳答案
how can you create an alias/pointer to a templated function?
你可以给函数指针类型的变量起别名:
template <typename T>
void foo()
{
std::cout << "foo!" << (T)3.14f << std::endl;
}
template <typename T>
constexpr void(*foo_alias)() = &foo<T>;
int main()
{
foo_alias<int>(); // 3
foo_alias<float>(); // 3.14
}
For example, if I want to be able to use the name
DurationCast
(...) What needs to be done to shorten the functionstd::chrono::duration_cast<T>()
to justDurationCast<T>()
?
函数指针的诀窍在于,您必须指定所有类型的参数才能获取函数的地址,因此,您需要显式给出或模板化所有参数的类型。不幸的是,std::chrono::duration_cast
接受三个参数:
template <typename T, class Rep, class Period>
constexpr T(*DurationCast)(const std::chrono::duration<Rep, Period>&) = &std::chrono::duration_cast<T, Rep, Period>;
std::chrono::seconds s(1);
std::chrono::milliseconds ms = DurationCast<std::chrono::milliseconds, float, std::ratio<1>>(s);
// ~~~~^ ~~~~~~~~~~~~^
// explicit representation and period
关于c++ - 给模板化函数取别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184190/