Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Templates

Templates

Scheduled Pinned Locked Moved C / C++ / MFC
c++wpfgraphicsdockerhelp
9 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Astricks
    wrote on last edited by
    #1

    I'm finding templates a bit hard to understand. I do understand some simple ones, but not everything. I looked at a sample program that finds max of two numbers and returns the bigger number. People say templates are generic but why not it take std::string into the function that finds of Max of two types(now it takes only numbers) We know that it's not sane to try "<" between strings but how does the compiler find the passed values are strings and reject it? and btw, how an STL container gets in anything we push? may it be numbers or strings, for example a vector. Can someone make a simple template program that just "holds" Object of any type, I just want to break the template barrier. Box <int> box_int; box_int.hold(1); Box <std::string> box_str; box_str.hold("Astricks"); Box <myClass> box_obj; box_obj.hold(myObj); Any help? Plz note: It's not a homework or assignement.

    M P 2 Replies Last reply
    0
    • A Astricks

      I'm finding templates a bit hard to understand. I do understand some simple ones, but not everything. I looked at a sample program that finds max of two numbers and returns the bigger number. People say templates are generic but why not it take std::string into the function that finds of Max of two types(now it takes only numbers) We know that it's not sane to try "<" between strings but how does the compiler find the passed values are strings and reject it? and btw, how an STL container gets in anything we push? may it be numbers or strings, for example a vector. Can someone make a simple template program that just "holds" Object of any type, I just want to break the template barrier. Box <int> box_int; box_int.hold(1); Box <std::string> box_str; box_str.hold("Astricks"); Box <myClass> box_obj; box_obj.hold(myObj); Any help? Plz note: It's not a homework or assignement.

      M Offline
      M Offline
      markkuk
      wrote on last edited by
      #2

      std::max() works just fine with std::string, and operator < has a well-defined meaning for strings.

      1 Reply Last reply
      0
      • A Astricks

        I'm finding templates a bit hard to understand. I do understand some simple ones, but not everything. I looked at a sample program that finds max of two numbers and returns the bigger number. People say templates are generic but why not it take std::string into the function that finds of Max of two types(now it takes only numbers) We know that it's not sane to try "<" between strings but how does the compiler find the passed values are strings and reject it? and btw, how an STL container gets in anything we push? may it be numbers or strings, for example a vector. Can someone make a simple template program that just "holds" Object of any type, I just want to break the template barrier. Box <int> box_int; box_int.hold(1); Box <std::string> box_str; box_str.hold("Astricks"); Box <myClass> box_obj; box_obj.hold(myObj); Any help? Plz note: It's not a homework or assignement.

        P Offline
        P Offline
        peterchen
        wrote on last edited by
        #3

        (1) Maybe you are expecting to much from templates. They are just a blueprint for the compiler, how to make functions or classes using the same code for different types. (2) It *is* sane to use "<" to compare std::string - it overloads operator < What you mean is probably that < doesn't do a string comparison for char * - and in this case, you are right: the "normal" min() template won't work template <typename T> T const & min(T const & a, T const & b) { return (a<b) ? a : b; } This template works for all types that implement a "sensible" operator <. It is generic for all typesthat fulfil this template parameter restriction In C++ you can even provide a specific implementaiton of a template function for a specific type. This is called template specialization: template<> char const * min(char const * a, char const * b) { return strcmp(a,b) < 0; } (Note: this isn't a recommended solution for the problem at hand, but an illustration of template specialization) The template saves you from writing the same min function for dozens (or thousads) of types. It does not save you from defining what "min" actually means in terms of C++ (3) Generally, writing correct templates is hard, because you have to be very precise about your template argument restrictions, and you have to keep "all" types in mind. Used correctly, templates avoid a lot of repetetive code, and are fairly simple to use. (4) What you ask is simple, but probably not what you want:

        template <typename T>
        class Box
        {
        T m_value;
        public:
        Box(T const & value) : m_value(value) {}
        T const & get_value() const { retrun m_value; }
        }

        However, you haven't broken any "template barrier": Box<string> is a completely different type from Box<int> there is no Box type that can hold both (Box is just a template for types, not a type by itself) What you want isn't simple. boost::any[^] implements a container type that can hold all kinds of types. (5) Try to read more[^] on templates, try to unde

        A 2 Replies Last reply
        0
        • P peterchen

          (1) Maybe you are expecting to much from templates. They are just a blueprint for the compiler, how to make functions or classes using the same code for different types. (2) It *is* sane to use "<" to compare std::string - it overloads operator < What you mean is probably that < doesn't do a string comparison for char * - and in this case, you are right: the "normal" min() template won't work template <typename T> T const & min(T const & a, T const & b) { return (a<b) ? a : b; } This template works for all types that implement a "sensible" operator <. It is generic for all typesthat fulfil this template parameter restriction In C++ you can even provide a specific implementaiton of a template function for a specific type. This is called template specialization: template<> char const * min(char const * a, char const * b) { return strcmp(a,b) < 0; } (Note: this isn't a recommended solution for the problem at hand, but an illustration of template specialization) The template saves you from writing the same min function for dozens (or thousads) of types. It does not save you from defining what "min" actually means in terms of C++ (3) Generally, writing correct templates is hard, because you have to be very precise about your template argument restrictions, and you have to keep "all" types in mind. Used correctly, templates avoid a lot of repetetive code, and are fairly simple to use. (4) What you ask is simple, but probably not what you want:

          template <typename T>
          class Box
          {
          T m_value;
          public:
          Box(T const & value) : m_value(value) {}
          T const & get_value() const { retrun m_value; }
          }

          However, you haven't broken any "template barrier": Box<string> is a completely different type from Box<int> there is no Box type that can hold both (Box is just a template for types, not a type by itself) What you want isn't simple. boost::any[^] implements a container type that can hold all kinds of types. (5) Try to read more[^] on templates, try to unde

          A Offline
          A Offline
          Astricks
          wrote on last edited by
          #4

          Thank you so much perterchen, Now I will sit on work on your explanation :). Thanks a lot :)

          1 Reply Last reply
          0
          • P peterchen

            (1) Maybe you are expecting to much from templates. They are just a blueprint for the compiler, how to make functions or classes using the same code for different types. (2) It *is* sane to use "<" to compare std::string - it overloads operator < What you mean is probably that < doesn't do a string comparison for char * - and in this case, you are right: the "normal" min() template won't work template <typename T> T const & min(T const & a, T const & b) { return (a<b) ? a : b; } This template works for all types that implement a "sensible" operator <. It is generic for all typesthat fulfil this template parameter restriction In C++ you can even provide a specific implementaiton of a template function for a specific type. This is called template specialization: template<> char const * min(char const * a, char const * b) { return strcmp(a,b) < 0; } (Note: this isn't a recommended solution for the problem at hand, but an illustration of template specialization) The template saves you from writing the same min function for dozens (or thousads) of types. It does not save you from defining what "min" actually means in terms of C++ (3) Generally, writing correct templates is hard, because you have to be very precise about your template argument restrictions, and you have to keep "all" types in mind. Used correctly, templates avoid a lot of repetetive code, and are fairly simple to use. (4) What you ask is simple, but probably not what you want:

            template <typename T>
            class Box
            {
            T m_value;
            public:
            Box(T const & value) : m_value(value) {}
            T const & get_value() const { retrun m_value; }
            }

            However, you haven't broken any "template barrier": Box<string> is a completely different type from Box<int> there is no Box type that can hold both (Box is just a template for types, not a type by itself) What you want isn't simple. boost::any[^] implements a container type that can hold all kinds of types. (5) Try to read more[^] on templates, try to unde

            A Offline
            A Offline
            Astricks
            wrote on last edited by
            #5

            Your example was so nice, realy useful. thanks a lot man. And I tried another simple thing, but why do I get this error peter?

            template class Key
            {
            T k;
            T* kptr;
            int length;
            public:
            Key(T);
            // ...
            };

            void main()
            {
            Key < int > i;
            }

            : error C2512: 'Key' : no appropriate default constructor available

            *

            P 1 Reply Last reply
            0
            • A Astricks

              Your example was so nice, realy useful. thanks a lot man. And I tried another simple thing, but why do I get this error peter?

              template class Key
              {
              T k;
              T* kptr;
              int length;
              public:
              Key(T);
              // ...
              };

              void main()
              {
              Key < int > i;
              }

              : error C2512: 'Key' : no appropriate default constructor available

              *

              P Offline
              P Offline
              peterchen
              wrote on last edited by
              #6

              If a coworker asked me that, I'd start with a "questions" game: What does the compiler say? Where does it saay that? etc. - you could work this out yourself ;) since you declare Key(T), the default constructor Key() is not generated automatically.


              Developers, Developers, Developers, Developers, Developers, Developers, Velopers, Develprs, Developers!
              We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
              Linkify!|Fold With Us!

              A 1 Reply Last reply
              0
              • P peterchen

                If a coworker asked me that, I'd start with a "questions" game: What does the compiler say? Where does it saay that? etc. - you could work this out yourself ;) since you declare Key(T), the default constructor Key() is not generated automatically.


                Developers, Developers, Developers, Developers, Developers, Developers, Velopers, Develprs, Developers!
                We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
                Linkify!|Fold With Us!

                A Offline
                A Offline
                Astricks
                wrote on last edited by
                #7

                oops, just a simple mistake. I'm taking up templates with an assumption it's too difficult to understand. So any error it throws look big for me . Sorry peter, it's the usual "no definition" error. Damn, I should have put Key(T){}. Now I defined it inline. Sorry for the stupid question. And Btw, next time if I come up with a good question would you try to extend your support? please?

                *

                P 1 Reply Last reply
                0
                • A Astricks

                  oops, just a simple mistake. I'm taking up templates with an assumption it's too difficult to understand. So any error it throws look big for me . Sorry peter, it's the usual "no definition" error. Damn, I should have put Key(T){}. Now I defined it inline. Sorry for the stupid question. And Btw, next time if I come up with a good question would you try to extend your support? please?

                  *

                  P Offline
                  P Offline
                  peterchen
                  wrote on last edited by
                  #8

                  No problem :) I just want to encourage you to help yourself.

                  Astricks wrote:

                  And Btw, next time if I come up with a good question would you try to extend your support? please?

                  No promise, but you aren't on a black list or something ;)


                  Developers, Developers, Developers, Developers, Developers, Developers, Velopers, Develprs, Developers!
                  We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
                  Linkify!|Fold With Us!

                  A 1 Reply Last reply
                  0
                  • P peterchen

                    No problem :) I just want to encourage you to help yourself.

                    Astricks wrote:

                    And Btw, next time if I come up with a good question would you try to extend your support? please?

                    No promise, but you aren't on a black list or something ;)


                    Developers, Developers, Developers, Developers, Developers, Developers, Velopers, Develprs, Developers!
                    We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
                    Linkify!|Fold With Us!

                    A Offline
                    A Offline
                    Astricks
                    wrote on last edited by
                    #9

                    peterchen wrote:

                    No problem I just want to encourage you to help yourself.

                    Thanks peter :).

                    peterchen wrote:

                    you aren't on a black list or something

                    pheww!:)

                    *

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups