I've finally started a deep dive into C++ templates. It's no news how incredibly powerful templates are; I've just not been able to fully master them. To be fair, templates have a steep learning curve and can certainly become complicated very quickly. On the bright side, the trade-off in flexibility and performance is often worth the effort. If you're asking how complicated it is? There's literally a 2500+ page book on C++ templates alone and several cppcon talks on it. You get the gist. For starters, a template in C++ is essentially a blueprint to tell the compiler how a function or a class should be defined (or created) at compile time. We basically tell the compiler to generate a family of functions or a family of classes during compile-time based on the parameterized type used during instantiation. Templates are similar to generics in other languages, albeit infinitely more powerful, flexible, and elegant than generics. Templates in C++ are a powerful mechanism for meta-programming since we get the compiler to generate code (or programs) based on the program we already wrote. One way I trivialize templates in my head is to assume that the compiler is running a subprogram during compilation. The output of this subprogram is executed as a part of the original program. So when you encounter a template definition in your code, pause and think of it as some process that runs during compilation. A key thing to note about templates: Templates are compiled using a two-phase compilation process: 1st phase: The compiler performs a static analysis of everything independent of the template parameters, static type checking, syntax, and grammar validation, non-templated signature validation, etc. 2nd Phase: The type is instantiated when the templated function or class is invoked. The compiler assesses the validity of the template parameters and the operations on these parameters. ref: https://lnkd.in/eZD-V3kE
Mastering C++ Templates: A Steep Learning Curve Worth the Effort
More Relevant Posts
-
#𝗕𝘂𝗶𝗹𝗱𝗲𝗿𝗣𝗮𝘁𝘁𝗲𝗿𝗻 Tell me what this code means: new User("Alice", "alice@mail.com", 30, "London", true, false, "PREMIUM") What is the 5th parameter? What is the 6th? Exactly. You have to check the constructor definition just to understand what you wrote. 𝘛𝘩𝘦 𝘗𝘳𝘰𝘣𝘭𝘦𝘮: 𝙃𝙖𝙧𝙙 𝙩𝙤 𝙧𝙚𝙖𝙙: A string of booleans and strings is a riddle, not a feature. 𝙀𝙖𝙨𝙮 𝙩𝙤 𝙢𝙞𝙨𝙪𝙨𝙚: Swapping two compatible types (like two booleans) creates silent bugs. 𝙈𝙖𝙞𝙣𝙩𝙚𝙣𝙖𝙣𝙘𝙚 𝙣𝙞𝙜𝙝𝙩𝙢𝙖𝙧𝙚: Adding a new field requires updating every single instantiation point. Many developers switch to setters to solve this, but that creates new issues. Setters lead to mutable objects that can be modified anywhere in the application, and they allow objects to exist in a "half-baked" state before they are fully initialized. 𝗧𝗵𝗲 𝗕𝘂𝗶𝗹𝗱𝗲𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻 𝗳𝗶𝘅𝗲𝘀 𝗯𝗼𝘁𝗵: Readable code: Each value is preceded by a descriptive method call. Immutable objects: The object is built in a separate step and then locked. Validation: You can enforce required fields and handle optional ones cleanly. 𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: The Builder Pattern is not just about cleaner syntax. It is a safety mechanism. It prevents invalid objects from ever reaching your production environment. This is why the Spring Framework uses it everywhere, from ResponseEntity and MockMvc to URI builders. It ensures that complex configurations are both human-readable and structurally sound. Full real-world explanation: [https://lnkd.in/gabG7yPF]
To view or add a comment, sign in
-
Ctrl+Z. You've used it a hundred times today. Ever wonder how it actually works? Every action you take — typing a word, deleting a line, changing a font — gets wrapped in a small object. That object knows two things: how to do the action, and how to undo it. Your editor keeps a stack of these objects. Ctrl+Z pops the last one and executes the undo operation. Ctrl+Y pushes it back and calls redo. The editor doesn't remember what you did. The objects do. That's the Command pattern. Instead of calling a function and forgetting about it, you turn the call into an object. Now you can store, queue replay it, or reverse it. Where you've already seen this: → Git commits — a diff that can be applied or reverted → Redux actions — `{ type: 'ADD_ITEM', payload }` dispatched to a store → Database transactions — statements that can be committed or rolled back → Task queues — jobs that sit in a queue until a worker picks them up and executes When NOT to use it: if your actions are simple and never need to be undone, queued, or logged. Wrapping every function call in an object when you'll never look at it again is a ceremony for nothing. #SoftwareEngineering #Programming #DesignPatterns #Architecture
To view or add a comment, sign in
-
Why do we use public static void Main(){} in C# ? static (The Most Critical Keyword):: This is the one that usually trips people up. In C#, you usually need to create an "instance" (an object) of a class to use its methods. The Catch: If Main were not static, the CLR would have to create an object of your class first. But to create an object, it needs to run code... and it can't run code until it finds Main. The Solution: By making it static, the method belongs to the class itself, not an object. The CLR can just call Program.Main() directly as soon as the app starts. public (The Gateway):: While modern C# (and certain compilers) allows private or internal entry points, public is the standard. Why: It tells the CLR, "This method is visible and accessible from outside this specific file/assembly." It ensures the execution engine has "permission" to walk through the front door of your code. void (The Result):: The Meaning: It tells the operating system, "I’m going to do my job and then just stop." The Alternative: Sometimes you’ll see static int Main(). In that case, the program returns a number (an Exit Code) to the OS. (e.g., return 0; means success, return 1; means an error occurred). Main (The Identifier):: The Rule: C# is case-sensitive. It must be capitalized Main. If you name it main, the compiler will look right past it and tell you that your program is missing an entry point.
To view or add a comment, sign in
-
Did you notice? df['date'].dt.year — No parentheses. df['date'].dt.month — No parentheses. df['date'].dt.day — No parentheses. df['date'].dt.day_name() — Parentheses required. If you have wondered why, this happens due to concept of attributes and methods in OOP. In Object Oreinted Programming (OOP), objects have two main features: Properties (Attributes): These are like nouns. They describe the state of an object. In layman's terms, properties (like .year) are like a locked box, you just open it and take what’s inside. For example, the year/month or day is fixed in a datetime, which you are extracting. It doesn't need to "calculate" anything for you. Methods: These are like verbs. They perform an action or a calculation. In simple terms, methods (like .day_name()) are like a vending machine, you have to "press buttons" (pass arguments) to tell it exactly what you want. For example, .day_name() is a method that can take input like 'locale'
To view or add a comment, sign in
-
-
ref vs out vs in vs this vs params in C# — Don’t Confuse These! These keywords look simple… But they control how data flows in your methods — and can impact performance, readability, and design. Let’s break them down 👇 🔹 ref — Pass by Reference (Read + Write) void UpdateValue(ref int x) { x = x + 10; } • Must be initialized before passing • Can be modified inside method Use when you want to read and update the same variable 🔹 out — Output Parameter (Write Only) void GetValue(out int x) { x = 100; } • No need to initialize before passing • Must be assigned inside method Common in methods like TryParse 🔹 in — Read-Only Reference (No Copy) void PrintValue(in int x) { Console.WriteLine(x); } • Passed by reference • Cannot modify inside method • Avoids copying large structs Great for performance optimization 🔹 this — Extension Method Keyword public static class Extensions { public static int Square(this int x) { return x * x; } } Usage: int result = 5.Square(); Makes methods look like part of existing types 🔹 params — Variable Number of Arguments int Sum(params int[] numbers) { return numbers.Sum(); } Usage: Sum(1, 2, 3, 4); Cleaner APIs when number of inputs is unknown Quick Comparison ref → read + write reference out → write-only output in → read-only reference this → extension methods params → variable arguments When to Use What ✔ Use ref → when method needs to modify input ✔ Use out → when returning multiple values ✔ Use in → for large structs (performance) ✔ Use this → for clean extension methods ✔ Use params → flexible method arguments Final Thought “Understanding parameter passing is not just syntax — it’s about controlling memory, performance, and intent.” Which one do you use the most in your projects? #csharp #dotnet #softwareengineering #backenddevelopment #cleancode #programming #dotnetdeveloper
To view or add a comment, sign in
-
-
Difference between var, dynamic, and object in C#? (INTERVIEW) 1) var (compile time) The compiler figures out the type from the value you assign and cannot change the type (compile error) - Cannot be null - Must be initialized when declared -> because compiler needs the value to know what type to use -Not recommended for function calls where return type is unclear -> because the type is not obvious to someone reading the code - Only works for local variables (not class fields) -> because it only works for local variables inside methods Best for: local variables where type is clear 2) dynamic (runtime) The type is resolved at runtime using the DLR (Dynamic Language Runtime) without the compiler checking - Can change type freely - Can be null - No compile-time errors (they become runtime crashes) - No IntelliSense - No type safety When you write int result = dyn + 10? the compiler does not check whether dyn supports the + operator, If dyn is an int at runtime it works but If dyn is a string then the code crashes Best for: COM, scripting languages, JSON without schema Never use in public APIs -> because no type safety 3) object (boxing & unboxing) The universal type of everything in C#, both value types and reference types inherit from object - Can change what it holds - Requires explicit casting to use original type - Cast can fail at runtime - Value types get boxed (performance cost) Creating many objects in a loop causes boxing each time which causes slower performance Best for: when you have no other choice -> old APIs 1. var → type obvious, cannot change 2. dynamic → runtime resolution, dangerous 3. object → need casting, boxing cost #INTERVIEW #var #object #dynamic #CSharp
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗢𝗣 𝗚𝘂𝗶𝗱𝗲 Stop writing long scripts with random functions. Organize your code into objects. Think of a house blueprint. A blueprint is a class. It is a plan. A builder uses one plan to build ten houses. Each house is an object. Classes define two things: - Properties: Data like color or name. - Methods: Actions like run or stop. Use the new keyword to create an object. This is instantiation. The constructor method runs when you create an object. It sets initial values. The this keyword assigns values to the specific object you create. Encapsulation bundles data and methods. It hides inner logic. Use a # symbol to make variables private. This stops external code from changing your data. OOP makes your code easy to reuse. It helps you scale your projects. Source: https://lnkd.in/gitXHVQE
To view or add a comment, sign in
-
So I checked out Typst. There's been so much talk about it, I had to give it a spin. It's more elegant than Asciidoc in some ways, prettier print, but is limited in others, and overall is a MUCH younger ecosystem. Overall? I wouldn't take the jump yet - for my requirements - but if you are a more design-focused team, PDF-only, and not overly focused on procedurals/integrations, I would seriously recommend you take it for a test drive. Note that Antora is working on a Typst backend - do not be surprised if Asciidoc-Typst becomes a practical print pipeline. 𝗧𝗵𝗲 𝗴𝗼𝗼𝗱: Gorgeous print without a lot of fuss: Can't add a lot to that. I often fall back on DocBook-XSL when handing off a professional print pipeline for Asciidoc, and, well, there is a reason for that. The bog-standard 𝚊𝚜𝚌𝚒𝚒𝚍𝚘𝚌𝚝𝚘𝚛-𝚙𝚍𝚏 is a fine tool, but it's not DocBook quality, and a far cry from LaTeX-quality you get from Typst. Typst conditionals are much more expressive: We're talking for-real actual full up 𝚒𝚏/𝚎𝚕𝚜𝚎 expressions vs Asciidoc 𝚒𝚏𝚍𝚎𝚏/𝚒𝚏𝚗𝚍𝚎𝚏/𝚒𝚏𝚎𝚟𝚊𝚕. #𝚕𝚎𝚝 𝚙𝚛𝚘𝚍𝚞𝚌𝚝 = "𝚂𝚞𝚙𝚎𝚛𝙿𝚕𝚊𝚗𝚎" #𝚒𝚏 𝚙𝚛𝚘𝚍𝚞𝚌𝚝 == "𝚂𝚞𝚙𝚎𝚛𝙿𝚕𝚊𝚗𝚎" [ 𝚃𝚑𝚒𝚜 𝚜𝚎𝚌𝚝𝚒𝚘𝚗 𝚊𝚙𝚙𝚕𝚒𝚎𝚜 𝚝𝚘 𝚂𝚞𝚙𝚎𝚛𝙿𝚕𝚊𝚗𝚎 𝚘𝚗𝚕𝚢. ] 𝚎𝚕𝚜𝚎 [ 𝙶𝚎𝚗𝚎𝚛𝚒𝚌 𝚌𝚘𝚗𝚝𝚎𝚗𝚝 𝚑𝚎𝚛𝚎. ] With how Typst interacts with the page (like TeX), the conditional can evaluate based on its page position. This is HUGE. Like, hard to not emphasize how huge this is. Kerning, OpenType features, glyph-level positioning, baseline shifts, and fine grid control. Asciidoc conditionals are very good; full 𝚒𝚏/𝚎𝚕𝚜𝚎 is better. 𝗧𝗵𝗲 𝗕𝗮𝗱 No spec Asciidoc is tied foot and jowel to DocBook, a no-nonsense old-school XML spec with XSD and DTD and all that stuff. The Typst spec is . . the Typst compiler. Picky transcludes. Typst transclusion uses #𝚒𝚗𝚌𝚕𝚞𝚍𝚎("𝚏𝚒𝚕𝚎.𝚝𝚢𝚙") for full file inclusion and #𝚒𝚖𝚙𝚘𝚛𝚝 for pulling in specific functions/variables from other files - ok, awesome . . . but the targets MUST be well-formed Typst files. No CSVs, no HTML, no line numbers, no tagged regions, no TextQL - it's got to have a function defined. Runtime attributes. AsciiDoc's conditional system integrates directly with the attribute ecosystem, so you can set attributes at build time via CLI (-𝚊 𝚙𝚛𝚘𝚍𝚞𝚌𝚝=𝚂𝚞𝚙𝚎𝚛𝙿𝚕𝚊𝚗𝚎) and have the entire document tree respond. Typst can do this with 𝚜𝚢𝚜.𝚒𝚗𝚙𝚞𝚝𝚜 but it is not much fun to troubleshoot. Very rough diagramming support. No Kroki, no asciidoctor-diagram, no Mermaid, no Vega or WireViz or any of the other toys. This stings a bit - those diagramming tools look like magic to people who haven't worked with them. Rough tooling. You thought you were off the reservation with Asciidoc? Whew boy. Everything here is pretty new, and you'll find yourself wrenching a bit. #typst #asciidoc #technicalwriting #docsascode #xml #dita #flare #ccms #ccs #pdf
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 𝗚𝘂𝗶𝗱𝗲 Stop gluing strings with plus signs. It creates messy code. It causes bugs. The old way is hard to read. You miss spaces. You struggle with new lines. Debugging takes too long. Switch to template literals. Use backticks instead of quotes. Here is why they work better: - Use ${} to insert variables. - Create multi-line strings without extra symbols. - Run math or functions inside the string. Compare the two styles: Old: 'Hello ' + name + '!' New: `Hello ${name}!` The new style is clean. You spot variables fast. Use this in your projects: - API responses for users. - Simple HTML templates. - Clear error logs. - SQL queries. Clean code scales better. Your teammates will thank you. Use backticks today. Source: https://lnkd.in/gXMYH5nu
To view or add a comment, sign in
-
-- "Two Edit Words” Problem — Lessons, Mistakes & Optimization -- Today I worked on an interesting DSA problem that tested attention to detail more than complex logic. -- Problem Summary - Given two arrays — queries and dictionary — the goal is to return all words from queries that differ by at most 2 characters from any word in the dictionary. -- My Approach - For each word in queries, compare it with every word in dictionary - Count the number of differing characters - If the difference is ≤ 2 → include it in the result - Simple nested loop + character comparison logic. ❌ Mistake I Made A small but critical syntax error: if (query[i]! = s[i]) 👉 This broke the entire logic because != was written incorrectly. -- Fixed it: if (query[i] != s[i]) -- This reminded me: -Even tiny syntax issues can cost a lot of debugging time. -- Optimization I Added Initially, I compared all characters even after exceeding 2 differences. Improved it by: if (diff > 2) break; -- This avoids unnecessary comparisons and improves performance. Also added: if (query.length() != s.length()) continue; - Focus on clean syntax — small errors matter - Always think about early exit conditions - Optimization is often about avoiding unnecessary work #DSA #CodingJourney #LeetCode #ProblemSolving #CPlusPlus #SoftwareEngineering #algorithm
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development