UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C++
  • » C++ Type inference from template without requiring C++0x?

#1 2009-01-07 02:18 AM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: C++ Type inference from template without requiring C++0x?

Hi all,

This is a straight C++ question for you... first, the example code.

template <typename T> class A
{
public:
   A() {}
   ~A() {}

   typedef T ItemType;
};

int main(int, char **)
{
   A<int> a;

   A<int>::ItemType x1 = 10;  // (A) this works

   a.ItemType x2 = 10;  // (B) this gives an error

   return 0;
}

As you can see above, I have a type that is declared as part of a templated class, and I'd like to be able to declare an item of that type on the stack, without having to manually type out the whole templated type.  That is, I'd like to use a declaration like (B), and not have to use one like (A).

Sine the compiler knows the type of (a), you'd think it would be able to figure out what a.ItemType is... but it doesn't.  I know that C++0x uses the "auto" keyword for this, but is there anything that can be done under the currently released versions of C++?

Thanks,
Jeremy

Offline

#2 2009-01-08 09:52 AM

Nope
Administrator
From: Germany
Registered: 2004-01-24
Posts: 385
Website

Re: C++ Type inference from template without requiring C++0x?

If you define a type within a class, you can only use it outside the class by giving the whole path as in

A<int>::ItemType

A typedefinition is no variable after all. Same goes for classes defined in classes.

class A
{
     B b;
     B::C c;
     class B
     {
          C c;
          ....
          class C
          {
                .....
          }

     }

}

main()
{
     A::B::C my_var;
     .....
}

Offline

#3 2009-01-08 04:15 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: C++ Type inference from template without requiring C++0x?

Nope;25869 wrote:

If you define a type within a class, you can only use it outside the class by giving the whole path as in

A<int>::ItemType

Sounds like I'm out of luck, then.  :(

Offline

  • Index
  • » C++
  • » C++ Type inference from template without requiring C++0x?

Board footer

Powered by FluxBB