CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2002
    Posts
    61

    copying unknown datatypes

    I have a variable in a templated class (A) that I want to be able to change from a wrapper class (B). The data type of A changes with each instance (string, int, float...), but what I'm wondering is if I can create a universal member function in B that will set the value in A?
    would it be possible to

    a = malloc(sizeof(*newVal));
    strcpy(a, newVal);

    where

    template <class T>
    class A
    {
    public:
    T * a;
    }

    and

    void * newVal;

    is this possible? and am I making sense?
    Last edited by DevLip; April 12th, 2004 at 12:00 PM.

  2. #2
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588
    First of all, the obvious question is: Why do you change a variable in class A in a function in class B? This violates the encapsulation priciple of OOP, so if there is no good reason to do this, you should consider a redesign. A better way would be to have accessor functions in class A, which can be used by class B. Something along the lines of
    Code:
    template <class T>
    class A
    {
    // ..
    public:
      T &get_Data() // should probably be const
      {
         return a;
      }
      void put_Data(const T &src)
      {
        a = src;
      }
    // ...
    };
    Ok, so what if you really have a good reason to violate this? Then you could make your member function in B also a template, if you have a compiler that supports member template functions. The code would be:
    Code:
    class B
    {
    // ...
    public:
      template <class T>
      void ChangeA(A<T> &val)
      {
        val.a = T(); 
      }
    // ...
    };
    Get this small utility to do basic syntax highlighting in vBulletin forums (like Codeguru) easily.
    Supports C++ and VB out of the box, but can be configured for other languages.

  3. #3
    Join Date
    Apr 2002
    Posts
    61
    you're right again...
    first way is the best, thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured