Re: stl template help

From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 08/10/04


Date: 10 Aug 2004 07:42:21 -0700


"Rich" <nomore@spam.com> wrote in message news:<A1XRc.3731$yh.2780@fed1read05>...

[ ... ]

> // The question is, how do I determine the type of class here?

The better question is, "How do I accomplish what I want WITHOUT
having to determine the type?" There are a _few_ situations where you
have little choice but to figure out the type and act appropriately,
but they're relatively rare and far between.

> // I need to do something like this:

I doubt you _need_ to do anything of the sort.
 
> if(arg.type == "integer"){
> // add / subtract
> }
> else if(arg.type == "string"
> // add some text to the string
> }

It's (barely) possible to do this in C++ by comparing typeid's, but
it's rife with shortcomings: it's error-prone, difficult to make
portable, difficult to extend, etc.

C++ has more direct support for (at least) three other methods:
polymorphism, operator overloading, and explicit specialization.

Polymorphism is based on inheritance instead of templates, so it may
not apply here.

Operator overloading does apply: in fact, under normal circumstances
it already handles the example you've given above. Using '+' will add
ints, and concatenate strings, just as you seem to want.

If/when neither of those will work, you can use explicit
specialization, which looks like this:

#include <iostream>
// The general template:
template <class T>
struct X {
    void func() {
        std::cout << "general template\n";
    }
};

// the special version for type int.
template <>
struct X<int> {
   void func() {
       std::cout << "int specialization\n";
   }
};

// the special version for type string
template <>
struct X<std::string> {
    void func() {
        std::cout << "string specialization\n";
    }
};

int main() {
        X<int> a;
        X<std::string> b;
        X<long> c;

        a.func();
        b.func();
        c.func();
}

Note that you don't have to include the code to figure out the type --
you just specify the action to take for each particular type, and the
compiler figures out which one applies when. Also note that each
specialization is more or less separate and independent, so adding a
new specialization doesn't require that you modify the existing code
at all.

> I understand that I can add a string field to the struct and just set it
> before using it... but is this the correct way?....

This can be useful at times, but this doesn't seem to be one of those
times.

-- 
    Later,
    Jerry.
The universe is a figment of its own imagination.


Relevant Pages