推导非类型模板参数 [英] Deduce non-type template parameter
问题描述
是否可以从模板函数参数中推导出非类型模板参数?
Is it possible to deduce a non-type template parameter from a template function parameter?
考虑这个简单的模板:
template <int N> constexpr int factorial()
{
return N * factorial<N - 1>();
}
template <> constexpr int factorial<0>()
{
return 1;
}
template <> constexpr int factorial<1>()
{
return 1;
}
我希望能够更改 factorial
,以便我可以调用它像这样:
I would like to be able to change factorial
so that I can alternatively call it like this:
factorial(5);
,让编译器在编译时找出N的值。
这是可能吗?
and let the compiler figure out the value of N at compile time. Is this possible? Maybe with some fancy C++11 addition?
推荐答案
除非你有时间机器,否则无法完成。
Can't be done, unless you have a time machine.
函数的参数在运行时处理。
The parameter to the function is handled at runtime. Yes, in your case it's a literal constant, but that's a special case.
在函数定义中,参数 types em>在编译时是固定的(因此,可以用于推导模板参数),但是参数只在运行时是固定的。
In function definitions, the parameter types are fixed at compile-time (and thus, can be used to deduce template parameters), but parameter values are only fixed at runtime.
为什么需要这个?是这样,你不必键入<>
的?
Why do you need this? Is it just so you don't have to type the <>
's?
这篇关于推导非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!