How to initialize a const primitive from a function returning a tuple with explicit type

86 Views Asked by At

I have a function that returns const values not by reference as in this question. I would like to call the function and initialize the const variables when I call the function but it isn't possible.

I tried declaring the variables but that is only possible if the variables are not const. Is there a way to intialize const variables by type after this call?

I tried the auto suggestion in this question's answer, which worked but I am surprised that it didn't work when I used size_t explicitly. Why wouldn't it work without auto? Isn't the type after using auto going to be size_t because this is what the function returns? I would like to use the explicit type to make it easier to read.

#include <tuple>
#include <cstddef>
#include <iostream>

using namespace std;

std::tuple<const size_t, const size_t> returnSize_T_Tuple() {
    const size_t i = 2;
    const size_t j = 3;

    return {i, j};
}

std::tuple<const int, const int> returnIntTuple() {
    const int i = 2;
    const int j = 3;

    return {i, j};
}

int main(){
    // const size_t s_i; // error: uninitialized ‘const s_i’ [-fpermissive]
    // std::tie(const size_t x, const size_t y) = returnSize_T_Tuple(); // error: expected primary-expression before ‘const’
    const auto [x,y] = returnSize_T_Tuple();
    const size_t [a,b] = returnSize_T_Tuple(); // error: structured binding declaration cannot have type ‘const size_t’ {aka ‘const long unsigned int’}

    cout << "x = " << x << "; " << "a = " << a;
}
1

There are 1 best solutions below

0
Péter Farkas On

According to P0217R3 proposed wording for structured bindings:

The auto type-specifier is also used to introduce a decomposition declaration (8.5 [dcl.decomp]).

So based on that, in this context auto isn't really a type specifier, it's just the syntax required for declaring a decomposition expression while being there as "something to stick const and ref-qualifiers onto".