element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ and STL : write code that is not dependent on the container type
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 12 Aug 2024 3:49 PM Date Created
  • Views 392 views
  • Likes 6 likes
  • Comments 2 comments
  • stl
  • c++23
  • OO
  • c++
  • teseo_c++
Related
Recommended

C++ and STL : write code that is not dependent on the container type

Jan Cumps
Jan Cumps
12 Aug 2024

The C++ Standard Template Library has a decent set of containers.  std::array, std::vector, std::list, ...

When you write a software function, it can be useful to handle whatever container the user wishes to use.

In my little print function here Slight smile , the logic can accept a rich set of std::string containers (and container ranges / views). It will call the stream operator of each element within the string.

#include <vector>
#include <array>
#include <string>
#include <ranges>

#include <iostream>

std::array <std::string, 2> a = {"arr", "ay"};
std::vector <std::string> v = {"vec", "tor"};

void print(const auto& range) {
	for (const auto& r: range) {
		 std::cout << r;
	}
	std::cout << std::endl;
}

int main() {
	print(a);
	print(v);
	auto r_a = std::views::all(a);
	auto r_v = std::views::all(v);
	print(r_a);
	print(r_v);
	return 0;
}

In this code, 4 containers and views are tested:

  • std::array<std::string, 2>: arrays have a fixed length
  • std::vector<std::string>: vectors have dynamic length
  • view over the array (in this case, a view that just contains all its elements)
  • view over the vector (in this case, a view that just contains all its elements)

All 4 can be handled by the function. If my function would try to perform an action that either the container, or the std::string within, can't handle, you get a compile time error.

Output:

array
vector
array
vector

If you wonder why I used the const and & constructs, or put the word contains in italics, ask. If you know, comment.
note: if you want to use methods or functions with auto parameters in a library, you have to include the implementation in the header file. That's similar to using templates (that are akin to auto).
Thanks for reading.

Link to all posts.

  • Sign in to reply
  • Jan Cumps
    Jan Cumps over 1 year ago

    There's also another alternative:

    Instead of accepting containers as auto, you can accept a std::span<of a particular type>

    void print(std::span<std::string> range)

    There are pros and cons

    con:

    • it only accepts artifacts that have a continuous set of date. a std::array, a std::vector or a classic C type array. And views/ranges based upon those.
    • there is overhead (tiny though)

    pro:

    • because you tell the span what data type is contained, your IDE and source insight/completion tools will work 
    • you don't have to put the implementation in the header file. This may be a thing if you have IP in the implementation.
    • again, no data is copied. The original container is where the data sits.
    • I prefer auto a lot. But preferably defined close to where it is used. Except if the library I'm writing is truly generic.
      In this case, I'm actually expecting an MNEO compatible reply. My lib is not that generic.
      This is not a rule but a style choice.

    The main difference is that it's known at writing time, what type of data is in your container.
    With auto, that info is known at compile time. Still very good :), because you will not be able to write programs that violate compliancy in both cases.

    I have a slight preference for the std::span in my Teseo library. Open for other positions.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps over 1 year ago

    This post was a preparation for adding flex to the ST Teseo GPS driver that I'm desining.

    I altered that library's code now to use auto: https://github.com/jancumps/gps_teseo_lib/pull/1/files. This does not cost anything at run time. No executable code is added or deleted.

    What it allows you to do, is make different decisions when you are using the library on a microcontroller, or on a Linux / Windows device.

    In some microcontroller designs, dynamic memory allocation is not allowed. For that reason, your architect may not allow you to use std::vector containers. Because they can be extended at runtime - and that may result in additional dynamic memory allocated. My library does not extend them - it has measures in place to never do that. But you know how a code review can go .
    By using the auto structure, you can now also use std::array containers. They are fixed size and don't have dynamic behavior.

    If you use this library on a Pi, BB or PC, you can use - and take advantage of -  the more dynamic containers. The code will work for both. With similar performance.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube