[英]constexpr non-static member function with non-constexpr constructor (gcc,clang differ)
[英]Calling non-static constexpr member function in template definition
#include <type_traits>
template<size_t S> struct A
{
constexpr size_t size() const noexcept { return S; } // Not static on purpose!
};
struct B : public A<123> {};
template <class T>
typename std::enable_if<std::is_base_of_v<A<T().size()>, T>, bool>::type // (*)
f(const T&, const T&) noexcept { return true; }
int main() {
B b1, b2;
f(b1, b2);
}
在 (*) 行中的原始问题中,我错误地使用了T()::size()
,这显然是不正确的,因为size()
不是 static。 该代码适用于T().size()
和std::declval<T>().size()
。 所以现在的问题是有什么区别,这些方法是否更正确或更好?
您没有指定您正在使用哪个编译器,但 gcc 的错误消息提供了一个很大的提示:
t.C:12:52: error: cannot call member function ‘constexpr size_t A<S>::size() const
[with long unsigned int S = 123; size_t = long unsigned int]’ without object
相应地调整方法的声明后:
static constexpr size_t size() noexcept { return S; }
gcc 然后编译显示的代码没有问题。
如果您的意图确实是让size()
成为常规的 class 方法,那么您需要在模板中使用std::declval
而不是将其作为 static 方法调用。
size
是非静态 function 并且需要 object 才能调用。 将其static
并删除const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.