为什么在编译时无法获取模板函数的参数计数?
Why can't I get the argument count of a template function at compile-time?
#include <cstddef>
template<typename... Types>
constexpr std::size_t getArgCount(Types&&...) noexcept
{
return sizeof...(Types);
}
struct A
{
int n;
void f()
{
static_assert(getArgCount(n) > 0); // not ok, why?
}
};
int main()
{
int n;
static_assert(getArgCount(n) > 0); // ok
}
为什么在编译时无法获取模板函数的参数计数?
错误信息:
1>test.cpp
1>test.cpp(17,45): error C2131: expression did not evaluate to a constant
1>test.cpp(17,42): message : failure was caused by a read of a variable outside its lifetime
1>test.cpp(17,42): message : see usage of 'this'
任何在上下文constexpr
之外访问this
的东西都不是常量表达式,如 [expr.const]/2.1 中所定义:
表达式 e 是核心常量表达式,除非e的计算遵循抽象机器的规则,将计算以下表达式之一:
this
,除了在constexpr
函数或作为e的一部分被评估的constexpr
构造函数中;
(我们需要this
才能访问n
,以便通过引用将其传递给getArgCount
(
所以这就是为什么第一种情况无法编译的原因。
第二种情况是编译的,因为它不涉及非常量的左值到右值转换(sizeof(n)
实际上并没有"读取"n
(。
为了演示这一点,还将编译以下内容:
struct A
{
int n;
void f()
{
int m = n;
static_assert(getArgCount(m) > 0); // ok, m doesn't need `this`
}
};
注意:如果引用的生存期始于该上下文,则在constexpr
上下文(Types&&
部分(中具有引用本身不会破坏"constexpr-ness":[expr.const]/2.11.2。
再比如:
struct A
{
int n;
void f()
{
static_assert(sizeof(n) > 0); // ok, don't need this for sizeof(A::n)
}
};
以下内容无法编译:
int n = 1;
static_assert(getArgCount(n+1) > 0); // not ok, (n+1) "reads" n
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数