约束函数会允许模板参数依赖于函数参数吗? [英] Will consteval functions allow template parameters dependent on function arguments?
问题描述
在C ++ 17中,此代码是非法的:
In C++17, this code is illegal:
constexpr int foo(int i) {
return std::integral_constant<int, i>::value;
}
那是因为即使foo
可以在编译时求值,编译器仍然需要产生指令以在运行时执行它,从而使模板实例化成为不可能.
That's because even if foo
can be evaluated at compile-time, the compiler still needs to produce the instructions to execute it at runtime, thus making the template instantiation impossible.
在C ++ 20中,我们将具有consteval
函数,这些函数需要在编译时进行评估,因此应删除运行时约束.这是否意味着该代码是合法的?
In C++20 we will have consteval
functions, which are required to be evaluated at compile-time, so the runtime constraint should be removed. Does it mean this code will be legal?
consteval int foo(int i) {
return std::integral_constant<int, i>::value;
}
推荐答案
否.
无论本文将进行何种更改,这点上,它都无法更改以下事实: -template函数定义只键入一次.此外,如果您建议的代码合法,那么我们大概可以找到一种声明类型为std::integral_constant<int, i>
的变量的方法,就ODR而言,这是非常禁止的.
Whatever changes the paper will entail, which is little at this point, it cannot change the fact that a non-template function definition is only typed once. Moreover, if your proposed code would be legal, we could presumably find a way to declare a variable of type std::integral_constant<int, i>
, which feels very prohibitive in terms of the ODR.
本文还指出,在其示例之一中,参数不打算被视为核心常量表达式;
The paper also indicates that parameters are not intended to be treated as core constant expressions in one of its examples;
consteval int sqrsqr(int n) {
return sqr(sqr(n)); // Not a constant-expression at this point,
} // but that's okay.
简而言之,由于可能存在键入差异,因此函数参数永远不会是常量表达式.
In short, function parameters will never be constant expressions, due to possible typing discrepancy.
这篇关于约束函数会允许模板参数依赖于函数参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!