我正在尝试使用嵌套 constexpr lambda 创建一个柯里化接口,但编译器不认为它是常量表达式。
namespace hana = boost::hana;
using namespace hana::literals;
struct C1 {};
template < typename T,
std::size_t size >
struct Array {};
constexpr auto array_ = [] (auto size) {
return [=] (auto type) {
return hana::type_c<Array<typename decltype(type)::type, size()>>;
};
};
int main() {
constexpr auto c1 = hana::type_c<C1>;
constexpr auto test = hana::type_c<Array<typename decltype(c1)::type, hana::size_c<100>()>>;
constexpr auto test2 = array_(hana::size_c<100>)(c1);
}
我之前发布了一个问题,因为我发现了一个不同的最小示例,但这还不够。
Error:
test2.cpp: In instantiation of ‘<lambda(auto:1)>::<lambda(auto:2)> [with auto:2 = boost::hana::type_impl<C1>::_; auto:1 = boost::hana::integral_constant<long unsigned int, 100>]’:
test2.cpp:31:54: required from here
test2.cpp:20:16: error: ‘__closure’ is not a constant expression
return hana::type_c<Array<typename decltype(type)::type, size()>>;
^~~~
test2.cpp:20:16: note: in template argument for type ‘long unsigned int’
test2.cpp: In function ‘int main()’:
test2.cpp:31:18: error: ‘constexpr const void test2’ has incomplete type
constexpr auto test2 = array_(hana::size_c<100>)(c1);
__closure is not a constant expression
:如果有人可以向我解释这个错误,那将是一个很大的帮助。我以前遇到过这个错误,但不记得为什么。
我将你的测试用例简化为:
#include <type_traits>
constexpr auto f = [](auto size) {
return [=](){
constexpr auto s = size();
return 1;
};
};
static_assert(f(std::integral_constant<int, 100>{})(), "");
int main() { }
正如上面评论中所说,发生这种情况是因为size
不是函数体内的常量表达式。这并不是 Hana 特有的。作为解决方法,您可以使用
constexpr auto f = [](auto size) {
return [=](){
constexpr auto s = decltype(size)::value;
return 1;
};
};
或类似的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)