C ++模板参数类型推导 [英] C++ template argument type deduction
问题描述
给出这样声明的模板化函数:
Given a templated function declared like this:
template<class T>
int Function(T object);
用户可以通过指定模板类型来调用此函数,如下所示:
A user can invoke this function by specifying the templated type, like this:
int result = Function<float>(100.f); // Valid
但是类型说明是可选的,因为编译器可以从T中推导出T的类型。提供的参数类型;像这样:
But the type specification is optional, as the compiler can deduce the type of T from the supplied argument's type; like this:
int result = Function(100.f); // Also valid, the compiler deduced the type "float" from the literal's type
推导得出 float类型稍微复杂一点,我想要这样的模板化值参数:
Let's say I get a little more complicated, and I want a templated value parameter like this:
template<class T, T* object>
int Function();
我可以这样调用我的函数:
I can call my function in this way:
static float val = 100.f;
// ...
int result = Function<float, &val>();
我的问题是:我有没有办法强迫编译器推断基于T的类型关于参数& val的类型?
我需要一种使以下代码有效的方法:
What I need is a way to make the following code valid:
static float val = 100.f;
// ...
int result = Function<&val>();
可以做到吗?
推荐答案
在C ++ 17中,您可以具有 auto
非类型模板参数。
In C++17, you can have auto
non-type template parameters. This will let you solve your problem.
类似 的东西:
template<auto object, class T=std::decay_t<decltype(*object)>>
int Function();
(假设您想在其中输入 T
类型 Function
)的正文
(assuming you want the type T
within the body of Function
)
在C ++ 14中,缺少C ++ 17功能。正是由于缺少它而添加了它。解决方法涉及诸如 #define UGLY_HACK(...)decltype(__ VA_ARGS __),__ VA_ARGS __
之类的宏。
In C++14, the C++17 feature is missing. It was added exactly because it was missing. Workarounds involve macros like #define UGLY_HACK(...) decltype(__VA_ARGS__), __VA_ARGS__
.
这篇关于C ++模板参数类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!