【发布时间】:2020-01-04 07:36:13
【问题描述】:
#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'
【问题讨论】:
-
看来你得把数据成员设为
nconstexpr。 -
注意主体没问题,其中n也不是constexpr。
-
我不确定;涉及
this指针时,事情变得复杂。 -
由于某种原因,如果将
int n = this->n;添加到f(),第一个断言也可以正常工作。 -
它也适用于
A().n和&A::n,但不适用于std::declval<A>().n。
标签: c++ c++11 language-lawyer constexpr static-assert