[英]How can I deduce a template parameter type in C++11?
I'm attempting to write a function that forces constexpr
evaluation via.我正在尝试编写一个强制
constexpr
评估的函数。 a template.一个模板。 I wrote this, but it works only for
int
(beware, will give recursion depth errors with GCC):我写了这个,但它只适用于
int
(当心,GCC 会产生递归深度错误):
#include <iostream>
template<int val>
constexpr int force_constexpr() { return val; }
constexpr int triangle(int n)
{
return n ? n + triangle(n - 1) : 0;
}
int main(void)
{
std::cout << force_constexpr<triangle(0x200)>() << '\n';
}
Note that this is for demonstration purposes only;请注意,这仅用于演示目的; I know that the triangle number can be calculated with
(n+1)*n/2
.我知道三角形数可以用
(n+1)*n/2
。
Then I attempted to write a generic function, however, that doesn't work as well.然后我尝试编写一个通用函数,但是,它不起作用。 This is a plain error (not surprising, as it uses
T
before T
is defined):这是一个普通的错误(并不奇怪,因为它使用
T
之前T
定义):
template<T val, typename T = decltype(val)>
constexpr T force_constexpr() { return val; }
as is this (which obviously won't work; it's a nested template):就像这样(这显然不起作用;它是一个嵌套模板):
template<typename T>
template<T val>
constexpr T force_constexpr() { return val; }
and this requires the type of the argument to be passed:这需要传递参数的类型:
template<typename T, T val>
constexpr T force_constexpr() { return val; }
How can I do this without passing the type as a parameter to the template?如何在不将类型作为参数传递给模板的情况下执行此操作? Or, in other words, how can I deduce a template parameter type?
或者,换句话说,我如何推导出模板参数类型?
I'm looking for a C++11 solution but solutions for other standards are welcome.我正在寻找 C++11 解决方案,但欢迎其他标准的解决方案。
You're looking for auto
template parameters, in C++17:您正在 C++17 中寻找
auto
模板参数:
#include <iostream>
template<auto T>
auto *singleton()
{
static const decltype(T) solo{T};
return &solo;
}
int main()
{
const int *p=singleton<42>();
std::cout << "The meaning of life: " << *p << std::endl;
return 0;
}
Specify the template parameter as auto
, and use decltype
to deduce its type.将模板参数指定为
auto
,并使用decltype
推断其类型。
I do not believe that this is possible before C++17, since this is precisely the use case for which auto
template parameters were added to the standard .我不相信在 C++17 之前这是可能的,因为这正是将
auto
模板参数添加到标准. Couldn't do this, conceptually, before then.在此之前,从概念上讲,无法做到这一点。
C++17 introduces auto
as non type template parameter: C++17 引入
auto
作为非类型模板参数:
template <auto val>
constexpr auto force_constexpr() { return val; }
Before, you have indeed blocked with之前,你确实屏蔽了
template<typename T, T val>
constexpr T force_constexpr() { return val; }
You can introduce MACRO to simplify usage:可以引入 MACRO 来简化使用:
#define AUTO(v) decltype(v), (v)
And then进而
std::cout << force_constexpr<AUTO(triangle(0x200))>() << '\n';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.