daviddoria 334 Posting Virtuoso Featured Poster

I'm not too familiar with boost::any, but do you have to any_cast to a boost::any? Or can you just use the object directly? That is if ( boost::any_cast<boost::any> (contrl->getObject(i)).type() == typeid(Physics::Box2D) ) vs if ( contrl->getObject(i).type() == typeid(Physics::Box2D) ) Also, you can see if the cast is failing with:

try
    {
        any_cast<some type>(yourobject);
        cout << "success";
    }
    catch(const boost::bad_any_cast &)
    {
        cout << "failure";
    }

You should definitely make sure this cast succeeds:

any_cast<Box2D> (contrl->getObject(i) )

before calling .Info() on the result.

daviddoria 334 Posting Virtuoso Featured Poster

Nope, 0%2 is fine: http://ideone.com/459Uh

daviddoria 334 Posting Virtuoso Featured Poster

Please change the cin statement to hard coded values 1) so we can exactly reproduce it and 2) so we know which values caused the problem. FPE means you are probably dividing by zero.

daviddoria 334 Posting Virtuoso Featured Poster

Sure, they'd have to provide a driver (that was included in my 20 line estimate :) ). The goal is to get questions posted in such a way that we can copy/paste/compile to see the error, then fix it easily. We can cut out all 3 steps of the copy/paste/compile with a codepad like system built in, and spend all of our energy fixing the problem.

daviddoria 334 Posting Virtuoso Featured Poster

@WaltP - Think of it more as serving as proof that the code works (well, at least compiles).

@Narue - After more thought, I disagree. I think plenty of the very beginner-style questions could/should be formed into a very short piece of "supposed to compile" code. By encouraging users to form the questions in this way it makes them very easy to solve as well as (in my experience) helps them come to the solution themselves. Posting 1000 lines of a tic tac toe game and asking why it doesn't work is not a good exercise for anyone. Extracting 20 lines that are causing a problem lets them inspect just the problem (in the absence of the "noise" of the rest of their project) closely and hopefully understand what is causing it.

daviddoria 334 Posting Virtuoso Featured Poster

Great. If the infrastructure is setup it, it could be mostly used in the code snippets section, but it could also be allowed in discussion threads when appropriate.

[compilable]

[/compilable]

:)

daviddoria 334 Posting Virtuoso Featured Poster

Would it be possible to integrate something like codepad.org or ideone.com into Daniweb? It would be really nice to see the compiler output of code snippets automatically. Consider the difference between

"Help something is wrong!"

#include <iostream>

int main()
{
 cout << hi;
 return 0;
}

and "Help something is wrong!"

http://codepad.org/xpzFkPA8

Of course we want the content to stay local so we don't want to encourage posting links to these external sites, but it also forces people to 1) ensure their code is supposed to be compilable and 2) ensure their error is explained clearly (at least from the compiler's point of view).

Thoughts?

David

daviddoria 334 Posting Virtuoso Featured Poster

I suggest simplying your entire code to about the same length as you have posted. You don't show us any non-virtual classes, and you don't show how AlphaBeta is constructed.

daviddoria 334 Posting Virtuoso Featured Poster

I would try Stack Overflow with the visual-studio-2010 tag:

http://stackoverflow.com/questions/tagged/visual-studio-2010

daviddoria 334 Posting Virtuoso Featured Poster

It looks like you are reading in all of the values, then only writing out the matrix once. What you have looks good, but I would suggest making it into a function, and using variable names that are descriptive:

void PrintMatrix(int matrix[10][10]; const int numberOfRows, const int numberOfColumns)
{
for(int row = 0; row < numberOfRows; row++)
{
  cout<<endl;
  for(int column = 0; column < numberOfColumns; column++)
  {
    cout<<a[i][j]<<" ";
  }
}
}
daviddoria 334 Posting Virtuoso Featured Poster

Is this a homework problem or do you really just want to get the numbers sorted? If so, use std::sort from <algorithm>

daviddoria 334 Posting Virtuoso Featured Poster

I would very much suggest you hard code values into the program as you debug. Once you're convinced it's working, then you can add in the user input. This will also help us help you - it would be very complicated to explain exactly the sequence of input values you used - whereas if you could post compilable code that demonstrates the problem that would be much easier. However, even if you post compilable and run-albe code, it is unlikely that anyone is going to debug your 200 lines. You really should attempt to narrow the problem down so we can look at a specific function or something like that.

daviddoria 334 Posting Virtuoso Featured Poster

If you use Qt for your GUI I've heard they have excellent internationalization support. You should ask here though: http://developer.qt.nokia.com/forums/ as this isn't really a c++ question.

daviddoria 334 Posting Virtuoso Featured Poster

Have you tried stepping through the code with a debugger? Once you do that, if you are still stuck, I would try to narrow down the problem. It is unlikely anyone is going to look through your 200 lines of code. If you can hardcode values into the program to get it into the last state you think it is correct, then you can ask a much more direct question. However, if you prepare the question correctly it is likely you will find your own answer :)

daviddoria 334 Posting Virtuoso Featured Poster

You could try posting here: http://www.gamedev.net/forum/25-opengl/

daviddoria 334 Posting Virtuoso Featured Poster

Every once in a while there is a thread with 0 replies that has been marked as "Solved":
http://www.daniweb.com/software-development/cpp/threads/398278

When you sort by "Unanswered", I don't think these threads should be displayed (they currently are: http://www.daniweb.com/software-development/cpp/unanswered/list/8). Going through "unanswered" threads is surely in an attempt to answer some, and you most likely won't answer a solved thread.

David

daviddoria 334 Posting Virtuoso Featured Poster

Please explain what the comment "// dosent work" on the connect call means. Also, you should probably look at some qt examples:
http://programmingexamples.net/wiki/Qt

and then ask on qt forums: http://developer.qt.nokia.com/forums/

This Daniweb forum is for pure c++.

David

daviddoria 334 Posting Virtuoso Featured Poster

QLabel::QLabel(const QLabel&) is called the copy constructor, and it is indeed private, so you cannot use it. You are trying to use it by copying your object when you pass it to the function. You should accept a const reference to the object instead:

void Test(const QLabel& yourLabel)

David

daviddoria 334 Posting Virtuoso Featured Poster

Please use code tags when you post code. Also, please use very small examples (5x5 images for example) to test. This way we can interpret the output instead of seeing full pages of stars.

WaltP commented: thanks for resurrecting an old post that even the OP didn't care about. -4
daviddoria 334 Posting Virtuoso Featured Poster

You might try linking to stdc++:

gcc yourcode.cpp -lstdc++

daviddoria 334 Posting Virtuoso Featured Poster

You are explicitly asking the user for the dimensions, so what is the problem? You have to assume either row-major or column-major (i.e. for:

1 2
3 4

row major ordering would be (1,2,3,4) where column major would be (1,3,2,4) ), but once you specify how you expect the input there is no reason to need line break characters, etc.

Also, please please please change variable names like 'd', and 'e' to "numberOfRows", etc.

David

daviddoria 334 Posting Virtuoso Featured Poster

I suggest you find a more specific forum. I.e. which framework are you using so that you have a text box? C++ does not have text boxes :)

daviddoria 334 Posting Virtuoso Featured Poster

Shouldn't the Patch class hold a pointer to the image to which it is a patch of? It would make a lot more sense if you had the Patch class to act as a view of the image. What is a Patch if it is not a sub-image?

I did it like this on purpose (though it might still be "wrong" haha). The idea is that all of the images are the same size, so if a patch is valid (inside) in one of them it is valid in all of them. The thought was that if I associate a specific image with a Patch, then I have to have the same patch duplicated for every image. Whereas if I am just describing a general region of an image with a Patch, it can be applied to any image. This was working fine until we introduced visitors :)

If the Patches would act as sub-images, you could simply visit all their pixels as you would when visiting all the pixels of an ordinary image. If you do that, I see no reason to pass the Image pointer down to the patch traversal algorithm, because that pointer would be encapsulated in the Patches themselves. And to answer the question, no, I don't think it is a good idea to pass down the image pointer, if that wasn't clear enough.

I agree that this part would be much easier if the Patch was actually related to an image.

I think …

daviddoria 334 Posting Virtuoso Featured Poster

I also realized that if I use a class template for a visitor:

template <typename TPixel>
class PixelPairVisitor
{
public:
  virtual void Visit(const TPixel& pixel1, const TPixel& pixel2) = 0;
};

That I wouldn't be able to put them in a container (as there is no superclass). However, c++ doesn't allow this:

class PixelPairVisitor
{
public:
  template <typename TPixel>
  virtual void Visit(const TPixel& pixel1, const TPixel& pixel2) = 0; //error: templates may not be ‘virtual’
};

How are you supposed to get a class template with a function that depends on the template parameter into a container??

daviddoria 334 Posting Virtuoso Featured Poster

(Following up on this discussion : http://www.daniweb.com/software-development/cpp/threads/405285/1732795#post1732795 )

Is it ok to store data in a Visitor class? In the case below, I have a Visitor named PixelWisePatchPairVisitor that internally needs to itself use a visitor. At some point the Image to visit needs to come into the picture. In this case I gave PixelWisePatchPairVisitor a pointer to the Image and then passed the image as a function argument to void VisitAllPixelPairs(TImage* image, TPixelPairVisitor& visitor) const. Is this ok?

#include <iostream>
#include <vector>

template <typename TPixel>
class PixelPairVisitor
{
public:
  virtual void Visit(const TPixel& pixel1, const TPixel& pixel2) = 0;
};

template <typename TPixel>
class SumOfDifferencePixelPairVisitor
{
public:
  SumOfDifferencePixelPairVisitor() : Sum(0) {}
  
  void Visit(const TPixel& pixel1, const TPixel& pixel2)
  {
    Sum += pixel1 - pixel2;
  }

private:
  TPixel Sum;
};

class PatchPair; // Forward declaration

class PatchPairVisitor
{
public:
  virtual void Visit(const PatchPair& patchPair) = 0;
};


class Region
{

};

class Patch
{
  Region region;
};

class PatchPair
{
public: 
  template <typename TImage, typename TPixelPairVisitor>
  void VisitAllPixelPairs(TImage* image, TPixelPairVisitor& visitor) const
  {
    for(int i = 0; i < 10; ++i)
      {
      // These need to be pixels from an image
      float sourcePixel = image->GetPixel(i);
      float targetPixel = image->GetPixel(i);
      visitor.Visit(sourcePixel, targetPixel);
      }
  }
private:
  
  Patch SourcePatch;
  Patch TargetPatch;
};


template <typename TImage, typename TPixelPairVisitor>
class PixelWisePatchPairVisitor : public PatchPairVisitor
{
public:
  PixelWisePatchPairVisitor(TImage* image) : InternalImage(image){}
  
  TPixelPairVisitor InternalPixelPairVisitor;
  
  void Visit(const PatchPair& patchPair)
  {
    patchPair.VisitAllPixelPairs(InternalImage, InternalPixelPairVisitor); // How does 'image' get here?
  }
private:
  TImage* InternalImage;
};

class …
daviddoria 334 Posting Virtuoso Featured Poster
First, to avoid the multiple presence of the base-class ImageBase, you must use virtual inheritance. Your problem here is actually called the "dreaded diamond" and is easily solved with virtual inheritance. Ideally, however, the CustomImageBase should not inherit from ImageBase because it is just an additional interface for your classes.

Ah, I did forget about virtual inheritance. However, it doesn't seem to work in my real case. In a simple example, it works:

#include <vector>

class ImageBase {};

template <typename TPixel>
class Image : public ImageBase {};

struct CustomImageBase : public virtual ImageBase
{
  virtual void DoSomething() = 0;
};

template <typename TPixel>
struct CustomImage : public Image<TPixel>, public CustomImageBase
{
  void DoSomething(){}
};

int main(int, char *[])
{
  CustomImage<float>* floatImage = new CustomImage<float>;
  floatImage->DoSomething();
  CustomImage<int>* intImage = new CustomImage<int>;
  intImage->DoSomething();

  std::vector<CustomImageBase*> images;
  images.push_back(floatImage);
  images.push_back(intImage);
  for(unsigned int i = 0; i < images.size(); ++i)
  {
    images[i]->DoSomething();
  }
  return 0;
}

However in the real case:

#include "itkImage.h"
#include "itkImageRegionIterator.h"

struct CustomImageBase : public virtual itk::ImageBase<2>
{
  virtual void DoSomething() = 0;
};

template <typename TPixel>
struct CustomImage : public itk::Image<TPixel, 2>, public CustomImageBase
{
  void DoSomething()
  {
    itk::Index<2> index;
    index.Fill(0);
    std::cout << this->GetPixel(index);
  }
};

int main(int, char *[])
{
  std::vector<CustomImageBase*> images;

  CustomImage<float>* floatImage = CustomImage<float>::New();
  CustomImage<int>* intImage = CustomImage<int>::New();

  return EXIT_SUCCESS;
}

(I can't inherit ImageBase from Image virtually as the FAQ suggests, though that doesn't seem to be necessary for it to work in my trivial example).

I get on this line (CustomImage<float>* floatImage …

daviddoria 334 Posting Virtuoso Featured Poster

@rubberman - thanks, I'll try to do that at some point. I found Umbrello which was able to import my classes, but unfortunately it does not draw the connections/dependencies automatically. Any suggestions for free programs that can do this?

@mike_2000_17 - the composite visitor is a great idea. This code is getting easier by the minute. The reason that I don't want an "image" type output that stores the values is that I need to sort them. Their ranking (sorted distance) is more important than their location in the image, but the location has to come along for the ride because I need it later. I take your point though, this is an awesomely flexible framework.

daviddoria 334 Posting Virtuoso Featured Poster

@mike_2000_17 - that does work, great. However it requires converting a hundred function templates into functors (yuck!).

I'm still curious about the inheritance method I suggested (CustomImage). If I'm going to have to change all of my functions, associating them with a class rather than leaving them as free functions seems like a better way to go.

daviddoria 334 Posting Virtuoso Featured Poster

By the way, the reason for this is that the user loads a bunch of images through a GUI and then I want to carry them all through a big process. I can't know the types of these images before hand, as they are read from the files the users selects. This seems like a pretty common case to want to handle, no?

daviddoria 334 Posting Virtuoso Featured Poster

Ok, none of these methods seem to make it "easy". I guess what I really want is to use the normal polymorphic style operations:

images[0]->DoSomething();
images[1]->DoSomething();

I'm happy to introduce new classes into the hierarchy, but that also doesn't seem possible without touching ImageBase/Image? Something like:

class CustomImageBase : public ImageBase
{
 virtual void DoSomething() = 0;
};

template<typename TPixel>
class CustomImage : public Image<TPixel>, public CustomImageBase
{
 void DoSomething();
}

main()
{
 std::vector<CustomImageBase*> images;
 images.push_back( new CustomImage<int> );
 images.push_back( new CustomImage<float> );
 images[0]->DoSomething();
 images[1]->DoSomething();
}

The problem with this is that Image inherits ImageBase, so then CustomImage inherits ImageBase twice :(

I tried to make CustomImageBase not derive from anything, but then it complains that there is no valid conversion when I try to add the objects to the vector. Are there any other tricks to try down this road?

daviddoria 334 Posting Virtuoso Featured Poster

@mike_2000_17 - I looked at boost::variant. It lets me add the items to the container (as long as I explicitly list all of the types I'm expecting in the variant template parameters), but then when I try to call the function template it tries to pass a boost::variant:

#include <iostream>
#include <vector>
#include <boost/variant.hpp>

class ImageBase { };

template <typename TPixel>
class Image : public ImageBase
{
public:
  TPixel GetPixel() const 
  {
    TPixel a = 3; return a;
  }
};

template<typename TImage>
void Output(const TImage* image)
{
  std::cout << image->GetPixel();
}

int main()
{
  std::vector<boost::variant< Image<int>*, Image<float>* > > images;

  images.push_back(new Image<float>);
  images.push_back(new Image<int>);
  Output(images[0]);
}

To pass an element as the correct type would require already knowing the type:

Output(boost::get<Image<int>*>(images[0]);

right?

daviddoria 334 Posting Virtuoso Featured Poster

@vijayan121 - your last suggestions is close to what I'm talking about. However, it seems you'd have to make a 'lookup' map for every function you want to call? yuck! Also, since the template parameter of image (e.g. image<int>) matches exactly the template parameter of the function (e.g. get_it<int>), is there not a way to make that map automatically without explicitly listing the types?

@mike_2000_17 - I'm still reading your post and looking into tuples. I'll get back to you.

daviddoria 334 Posting Virtuoso Featured Poster

There are two classes, ImageBase, and template <T> Image in a library I'm using. I want to store many of these images in a container, and then pass them to a function templates that expect an Image<T>. The only thing I knew to do was store ImageBase* in the container:

#include <iostream>
#include <vector>

class ImageBase { };

template <typename TPixel>
class Image : public ImageBase
{
public:
  TPixel GetPixel() const 
  {
    TPixel a = 3; return a;
  }
};

template<typename TImage>
void DoSomething(const TImage* image)
{
  TPixel pixel = image->GetPixel(); // Dummy call to an Image function 
}

int main(int, char *[])
{
  std::vector<ImageBase*> images;
  ImageBase* image = new Image<float>;
  images.push_back(image);
  ImageBase* image2 = new Image<int>;
  images.push_back(image2);

  //DoSomething(images[0]); // no member named GetPixel

  return 0;
}

but of course passing an ImageBase to a function that calls a function expecting a type Image (using functions defined in Image and not in ImageBase) doesn't make sense. Of course I could add pure virtual functions in ImageBase and implement them in Image, but then I will be using a modified version of the library, which is huge headaches for users. Is there a way to do this without touching ImageBase?

Thanks,

David

daviddoria 334 Posting Virtuoso Featured Poster

I think I'm getting the hang of it. I have a visitor setup for single Patch objects.

https://github.com/daviddoria/PatchBasedInpainting/blob/master/Patch.hxx
https://github.com/daviddoria/PatchBasedInpainting/blob/master/PixelSumAccumulator.h
https://github.com/daviddoria/PatchBasedInpainting/blob/master/Tests/TestPixelSumAccumulator.cpp

For the real case of finding the difference between the two patches in a PatchPair object, I made a visitor that accepts two pixels in its Visit function (Visit(pixel, pixel)).

https://github.com/daviddoria/PatchBasedInpainting/commit/49b05e6327a48dc0c64fb4e9ef783d87a12e36e1

I see now that I can create a vector<PixelPairVisitor> and then apply all of these visitors to compute the differences I am interested in.

---------

I'm still uneasy about removing the PairDifferences object from the PatchPair object. I guess it depends on what you return from a PatchDifferenceVisitor that gets applied to a whole image. With the PixelDifference visitors, we are actually accumulating so we intentionally lose the localization of the differences. With the PatchDifferenceVisitor, would you return a vector<std::pair<PatchPair, float> >? If so, to apply more than once visitor which each computes a different difference, would you do something like this:

vector<PixelPairVisitor> visitorsToApply;
typedef vector<std::pair<PatchPair, float> > SinglePass;
vector<SinglePass> AllDifferences;

for all 'visitor' in visitorsToApply
{
  AllDifferences[i] = image.VisitAllPatches(visitor)
}

// Combine AllDifferences into a vector<std::pair<PatchPair, PairDifferences> >

That would work, but it seems dangerous. Thoughts?

daviddoria 334 Posting Virtuoso Featured Poster

I'm slowly getting the idea... I wrote a couple of examples here:
http://stackoverflow.com/questions/8771932/the-use-of-an-accept-in-the-visitor-pattern

Mike, in your code example, you have implemented visitPixel(GreyPixel) and visitPixel(ColorPixel) both inside AveragingVisitor. I've also seen this in most of the examples I've been looking at. Is there a reason for doing that, as opposed to writing a AveragingColorPixelVisitor, and an AveragingGreyPixelVisitor? It seems like the logic has to be duplicated anyway, so why not keep them totally separate? In my case, this would be an AveragingPixelVisitor and an AveragingPatchVisitor - if they are separate then the AveragingPixelVisitor won't depend on the Patch class, which seems like a good thing.

daviddoria 334 Posting Virtuoso Featured Poster

Mike,

First, thank you for taking the time to look at this! I really appreciate it.

I was pretty confident it was bad, I just didn't know why :)

One concrete problem with your design is this idea that somehow the "difference" method should be a part of the "patch-pair" or "self-patch-compare" classes.

You are suggesting that the differences should NOT be contained in the PatchPair, right?

PatchPair defines the input data for a binary mapping of some kind (e.g. PatchPair -> float (difference), or PatchPair -> Patch). The SelfPatchCompare is basically a folding method (iterates over a set of patches, and then combines all the individual results into one (fold or "accumulator")). This issue is basically what is causing the main problem you stated, and my answer is that both solutions you proposed are bad, and my answer to your problem is to avoid this awkward mix of responsibilities.

This certainly is the main problem. The reason I had decided to put the differences inside the PatchPair is that they are tightly coupled. That is, if I have a vector<PatchPair> and a vector<float> storing the differences, those vectors must remain identical in order and length. That is, if I did a sort on the differences vector, I would no longer know which PatchPair each difference corresponded to. By this folding/accumulation you are suggesting, how do the differences stay associated with their generating PatchPair?

Another concrete problem with your code is that you are over-restricting …

daviddoria 334 Posting Virtuoso Featured Poster

I thought I would have to specify it explicitly because in my real case the function parameter was actually a template parameter of the class that the function is inside of. But I think it is working properly automatically deducing it, thanks!

daviddoria 334 Posting Virtuoso Featured Poster

I have been working with this code for quite a long time now, and I continually refactor and refactor and just keep running into different forms of the same problem. In the last couple of weeks I've tried to take a step back and really think about the design, motivated by the fact that the code was nearly impossible to write tests for (I read a book on TDD :) ). Below is the design I've converged on.

The program's job is to solve an image processing problem - the high level outline (hopefully from bottom to top) of the part of the design I'm interested in is:

- A Patch objects that define a square region in an image

- A PatchPair class that holds two patches to be compared

- A PixelDifference class that has a float Difference(PixelType, PixelType) function.

- A template PatchDifference<typename TPixelDifference> class that sums the difference corresponding pixels in a PatchPair using the provided PixelDifference class.

- A PairDifferences class that stores a collection of different difference types. Each PairPair has a PairDifferences object.

- A template SelfPatchCompare<typename TPatchDifference> that compares a specified patch to all other patches in an image

- A PatchBasedInpainting class. This is the object that would be instantiated from main(). The logic of this class is not the concern of the part of the design I'm worried about. The one part that it does involve is that at some point it …

daviddoria 334 Posting Virtuoso Featured Poster

Gah I always forget about optimizations. I get the same result, thanks.

daviddoria 334 Posting Virtuoso Featured Poster

I read that using a policy class for a function that will be called in a tight loop is much faster than using a polymorphic function. However, I setup this demo and the timing indicates that it is exactly the opposite!? The policy version takes between 2-3x longer than the polymorphic version.

#include <iostream>

#include <boost/timer.hpp>

// Policy version
template < typename operation_policy>
class DoOperationPolicy : public operation_policy
{
  using operation_policy::Operation;

public:
  void Run(const float a, const float b)
  {
    Operation(a,b);
  }
};

class OperationPolicy_Add
{
protected:
  float Operation(const float a, const float b)
  {
    return a + b;
  }
};

// Polymorphic version
class DoOperation
{
public:
  virtual float Run(const float a, const float b)= 0;
};

class OperationAdd : public DoOperation
{
public:
  float Run(const float a, const float b)
  {
    return a + b;
  }
};

int main()
{
  boost::timer timer;

  unsigned int numberOfIterations = 1e7;

  DoOperationPolicy<OperationPolicy_Add> policy_operation;
  for(unsigned int i = 0; i < numberOfIterations; ++i)
    {
    policy_operation.Run(1,2);
    }
  std::cout << timer.elapsed() << " seconds." << std::endl;
  timer.restart();

  DoOperation* polymorphic_operation = new OperationAdd;
  for(unsigned int i = 0; i < numberOfIterations; ++i)
    {
    polymorphic_operation->Run(1,2);
    }
  std::cout << timer.elapsed() << " seconds." << std::endl;

}

Is there something wrong with the demo? Or is just incorrect that the policy should be faster?

daviddoria 334 Posting Virtuoso Featured Poster

Interesting, it seems that 'class' and 'typename' differ in template template parameters:

template <template <typename> class T>
vs
template <template <typename> typename T> // doesn't work

I thought they were synonymous. I guess I was wrong!

daviddoria 334 Posting Virtuoso Featured Poster

Very cool, thanks!

daviddoria 334 Posting Virtuoso Featured Poster

I am not familiar with this syntax, but I think it may be what I want:

template <template <class> class U>

Is this called something that I can go look up?

daviddoria 334 Posting Virtuoso Featured Poster

Hm, I thought that was what I wanted, but that requires the POD type (inner template parameter) to be passed implicitly. What about this:

#include <iostream>
#include <vector>

template <typename T>
void Output(const T& object)
{
  std::cout << object << std::endl;
}

template <typename C>
class MyClass
{
};

// Handles MyClass<int>, MyClass<float>, MyClass<anything>
template <typename T>
void Output( const MyClass<T>& object)
{
  std::cout << "Special " << std::endl;
}

int main(int argc, char* argv[])
{
  MyClass<double> myClass;
  //Output(myClass);
  Output<MyClass<double> >(myClass);

  Output(2u);

  return 0;
}

Here the type of the argument is explicitly stated, and it doesn't work (I think it tries to instantiate with MyClass<MyClass<double> >.

I need this because I am actually trying to overload a function inside of a class:

#include <iostream>
#include <vector>

template <typename T>
class Simple
{
};

template <typename T>
class MyClass
{
public:

  void Output(const T& object)
  {
    std::cout << "NON-MyClass" << std::endl;
  }

  // I want this to handle MyClass<int>, MyClass<float>, MyClass<anything>
  void Output( const MyClass<T>& object)
  {
    std::cout << "MyClass" << std::endl;
  }
};


int main(int argc, char* argv[])
{
  MyClass<double> myClass;
  myClass.Output(2.0f);

  Simple<int> mySimple;
  MyClass<Simple<int> > myClass2;
  myClass2.Output(mySimple);

  return 0;
}

Thoughts?

David

daviddoria 334 Posting Virtuoso Featured Poster

I have a feeling that I can come up with a much better title for this thread once I know the answer to this question :).

Say I have a function template template <typename T> void MyFunction(). Now I want to specialize MyFunction for a templated type. That is, say I have template <typename C> class MyClass{}; Now I want to specialize MyFunction for any MyClass<C> that was passed as the template parameter to MyFunction. Is this possible?

The structure would be something like this:

#include <iostream>
#include <vector>
 
#include "Point.h"
 
template <typename C>
class MyClass
{
};
 
template <typename T>
void Output(const T& object)
{
  std::cout << object << std::endl;
}
 
// I want this to handle MyClass<int>, MyClass<float>, MyClass<anything>
template <>
void Output<MyClass<C> >(const MyClass<C>& object)
{
  std::cout << "unsigned int " << object << std::endl;
}
 
int main(int argc, char* argv[])
{
  MyClass<double> myClass;
  Output(myClass);
 
  Output(2u);
 
  return 0;
}

Any ideas?

Thanks,

David

daviddoria 334 Posting Virtuoso Featured Poster

pseudorandom21 - I am not using Boost at all, but rather compiling with the gnu-c++0x flag. Also, your compiler must not be very strict if it allows this :).

Rashakil Fol - Oh right, I forgot it was expecting non-const reference, which of course means the object being passed must not be const. However, I guess I don't understand why the object that was getting passed was const?

daviddoria 334 Posting Virtuoso Featured Poster

Can anyone explain why I can't sort this vector:

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
 
struct Test
{
public:
  Test(const unsigned int input) : a(input){}
  int a;
};
 
struct SortFunctor
{
  bool operator()(std::shared_ptr<Test>& object1, std::shared_ptr<Test>& object2)
  {
    return(object1->a < object2->a);
  }
};
 
//////////////////////////
int main (int argc, char *argv[])
{
  srand(time(NULL));
 
  std::vector<std::shared_ptr<Test> > objects;
  std::shared_ptr<Test> object1(new Test(rand()%50));
  objects.push_back(object1);
 
  std::shared_ptr<Test> object2(new Test(rand()%50));
  objects.push_back(object2);
 
  std::sort(objects.begin(), objects.end(), SortFunctor());
 
  return 0;
}

http://ideone.com/LoNoC - it complains "no known conversion for argument 1 from ‘const std::shared_ptr<Test>’ to ‘std::shared_ptr<Test>&’

It works if I changie the functor operator() to be const std::shared_ptr<Test>, but can't you always pass a mutable object to a function expecting a const object?

Thanks,

David

daviddoria 334 Posting Virtuoso Featured Poster

I want to sort the container of pointers to const objects via an indirect_iterator: http://ideone.com/r5qBu - is this not possible (for the same reason that storing const objects in the vector directly is not possible - that the assignment operator doesn't make sense)?

daviddoria 334 Posting Virtuoso Featured Poster

You are right! I just made an example of this here: http://programmingexamples.net/wiki/CPP/Boost/Iterators/IndirectIterator

daviddoria 334 Posting Virtuoso Featured Poster

If I want to expose an iterator to a class member container, I can do so like this:

class PatchCollection
{
public:
  // Iterator interface
  typedef std::set<Patch>::iterator iterator;
  typedef std::set<Patch>::const_iterator const_iterator;

  iterator begin() { return SourcePatches.begin(); }

  iterator end() { return SourcePatches.end(); }

private:

  std::set<Patch> Patches;
};

However, if the member has to be a std::set<Patch*>, but I want the class's iterator to act like it is iterating over a set::<Patch> instead, what would I have to do?

Thanks,

David