c++ - 给模板化函数取别名

标签 c++

您可以使用 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 function std::chrono::duration_cast<T>() to just DurationCast<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

DEMO

关于c++ - 给模板化函数取别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184190/

相关文章:

c++ - 实现多线程 UDP 服务器(线程池?)的问题

c++ - 使用 Boost Ublas lu_Factorize 时出错

使用预定义参数引用 C++ 函数

c++ - boost::filesystem 添加引号?

c++ - 使用 new 创建一个结构数组

c++ - 我们是否可以通过将#if-#else if和宏与参数结合起来,在C和C++中实现预处理程序级别的决策?

c++ - 修改调用另一个类函数的类中的变量

android - 如何理解 android ndk (c++) 中的崩溃原因

c++ - 在不丢失数据的情况下将子类对象存储在同一个容器中?

c++ - 如何将 vector<string> 转换为 null 终止的 char **?