Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I include <tuple>?

Tags:

c++

header

I am a newbie in c++, and I suspect, that, of course the question relates not only to tuple.

So, I've watched a tutorial with roughly this code:

#include <tuple>

std::tuple<...> t(...)

Why #include <tuple>? Especially, given the fact that we explicitly write std::tuple. The code compiles without that #include line just well...

like image 947
Nurbol Alpysbayev Avatar asked Mar 04 '26 19:03

Nurbol Alpysbayev


2 Answers

Because <tuple> is a header file which contains the tuple class inside the namespace std. Just because you're explicitliy saying std:: doesn't mean the compiler will just be able to find it if it's not included.

The reason it worked for you in this case is probably because another header you have included already includes <tuple> and thus your code includes <tuple> indirectly or because the compiler you're building with includes it automatically. This is not guaranteed by the standard and should not be relied upon. Always include the headers you'll need to make your code portable.

like image 195
Hatted Rooster Avatar answered Mar 06 '26 07:03

Hatted Rooster


You always should include the specific headers for any types that you use in your code.

The code compiles without that #include line just well...

That your code compiles without is just by chance, because it might have been included by another standard header you use in your program, and not guaranteed by the standard, and thus not portable.

Especially, given the fact that we explicitly write std::tuple.

The explicit use of the std:: namespace doesn't have any significance about that rule.

You should also always be explicit about using classes or types from the std namespace to prevent getting into ambiguity troubles.

Related stuff:

  • Why is “using namespace std;” considered bad practice?
  • Why should I not #include ?
  • How do I include the string header?
like image 42
πάντα ῥεῖ Avatar answered Mar 06 '26 08:03

πάντα ῥεῖ