2

Question is really simple, why is this code not working:

#include <tuple>

int main( int argc, char* argv[]) {
    const int a,b = std::tie(std::make_pair(1,2));
    return EXIT_SUCCESS;
}

g++ gives me this error:

./test.cpp: In function ‘int main(int, char**)’: ./test.cpp:4:13: error: uninitialized const ‘a’ [-fpermissive] const int a,b = std::tie(std::make_pair(1,2)); ^ ./test.cpp:4:42:

error: cannot bind non-const lvalue reference of type ‘std::pair&’ to an rvalue of type ‘std::pair’
const int a,b = std::tie(std::make_pair(1,2));

I cannot get any tuple-like return by value, using this kind of pattern (either const or non const). Is it a better way to do what I am trying to achieve here ?

1
  • 4
    std::tie does not "unpack" tuples and C++ is not Python. This looks like you are writing C++ based on guessing, which does not work. Commented Oct 25, 2017 at 12:03

1 Answer 1

11
const int a,b = std::tie(...)

This isn't doing what you think it is. It's creating two const int variables:

  • a, uninitialized

  • b, initialized to std::tie(...)


The proper way of using std::tie is as follows:

int a, b;
std::tie(a, b) = std::make_pair(1, 2);

Note that you need a and b to be already declared and non-const.


In C++17, you can use structured bindings instead:

const auto [a, b] = std::make_pair(1, 2);
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I am really dumb, I just realized that 1 minute ago. Cannot delete question now.
@Tobbey - Good. Vittorio doesn't deserve to have his effort go down the drain because you had an "oops" moment. That's why SO prohibits you from deleting.
You are right, anyway despite my comment Vittorio Romeo answer is interesting because I discovered that c++17 allows to do exactly what I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.