简体   繁体   English

C ++ Constexpr功能

[英]C++ Constexpr Function

could anyone help me to understand why this code snippet won't compile? 任何人都可以帮助我了解为什么这个代码片段将无法编译?

#include <iostream>
#include <tuple>
#include <string_view>

constexpr auto Fields()
{
    using namespace std::string_view_literals;

    return std::tuple(
        std::tuple("campo_1"sv, 123),
        std::tuple("campo_2"sv, 456),
        std::tuple("campo_3"sv, 890),
        std::tuple("campo_4"sv, 136));
}

template<typename Tuple>
constexpr auto ProcessTupleElement(Tuple &&tuple)
{
    //constexpr auto ccb = std::get<1>(tuple); // 1 uncomment to get an error
    //char sx[ccb]; // 1 uncomment to get an error
    //(void)sx;
    return std::get<1>(tuple);
}

template<typename Tuple>
constexpr auto IterateTupleImpl(Tuple &&t)
{
    return ProcessTupleElement(std::get<0>(std::forward<Tuple>(t)));
}

template<typename Tuple>
constexpr auto IterateTuple(Tuple &&t)
{
    return IterateTupleImpl(std::forward<Tuple>(t));
}

int main()
{
    constexpr auto aa = IterateTuple(Fields()); // 2
    char sx[aa];
    (void)sx;
    return 0;
}

The code is just for testing purposes, I'm trying to figure out why in main function (comment "2") I'm able to define a constexpr variable which I then use to define a C-array size, but trying to do the same in function ProcessTupleElement (marked whit comment "1") I'm receiving a compiler error saying that: 该代码只是出于测试目的,我想弄清楚为什么在main函数(评论“2”),我能够定义一个变量constexpr我,然后用它来定义一个C数组的大小,而是试图做在函数ProcessTupleElement相同(标记为白色注释“ 1”),我收到一个编译器错误,内容为:
prog.cc:19:20: error: '* & tuple' is not a constant expression
19 | constexpr auto ccb = std::get<1>(tuple);
prog.cc:20:10: error: size of array is not an integral constant-expression
20 | char sx[ccb]; // 1

As extra information, I'm compiling with GCC (C++ 17). 作为额外的信息,我与海湾合作委员会(C ++ 17)编制。 My idea behind this test is to iterate in compile time a tuple like the one defined inside Fields function to test whether it has repeated names, but I can't manage to solve a previous problem, IE constexpr ness of function + variables. 我的这个测试背后的想法是在编译时遍历像里面定义的一个元组Fields功能,以测试它是否已经重复的名字,但我不能设法解决前面的问题,IE constexpr内斯的功能+变量。

argument are not constexpr (even when use with constexpr at call site). 参数不是constexpr(即使在调用站点与constexpr一起使用时)。

Remember that constexpr function might be called as regular function. 请记住,constexpr函数可能被称为常规函数。

Btw, you might have simplified your example to 顺便说一句,您可能已将示例简化为

constexpr int identity(int n)
{
    // constexpr int i = n; // Invalid
    return n;
}

constexpr int the_answer = identity(42);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM