vijayan121 1,152 Posting Virtuoso

> In reality FuncA is a normal function in an exe, and FuncB is a function on a COM interface
> (so FuncA actually calls CoCreateInstance before calling FuncB on the COM object).
> And inside FuncB, DoSomethingElse is actually an ADO function that i am calling
> on one of microsoft's ADO COM components.
> i do not think these details are relevent to my question ...
these details are *very* relevant to your question. the innermost scope of execution of a com object is an apartment. unless the thread in your exe and the com objects involved are in the same apartment (either the MTA or the same STA), remoting is involved. what looks like an object to you (what was returned by CoCreateInstance) would really be a proxy; the method call would be forwarded to another thread which is in the same apartment as the object on which the method is invoked. c++ exceptions cannot be thrown or caught across thread boundaries (there is a separate stack for each thread). to marshal exceptions across apartment boundaries, use the COM exception mechanism (IErrorInfo).

vijayan121 1,152 Posting Virtuoso

the problem is that you are calling a virtual function during the construction of the base class. this will not behave the way you expect it to behave; the wrong vtable is being pointed to at the time. if you call virtual functions during construction or destruction, such calls will never be dispatched to a more derived class than the one that is currently being constructed or destroyed.
for a more detailed explanation of why this is so (and why it is a good thing) and a possible work around, see http://www.artima.com/cppsource/nevercall.html

vijayan121 1,152 Posting Virtuoso

> my first time using shared memory and I'm really discouraged.
it is just that the problem is (much) harder than you imagine it to be.

for this to work, a shared memory segment should be created once and when allocate is called we have to sub-allocate memory blocks out of this segment. a good place to learn about a simple way of doing it is to read the section on implementing malloc() and free() in 'The C Programming Language' (Kernighan and Ritchie).

now we encounter the first problem: when creating shared memory (and memory mapped files) to communicate between two processes, the memory segment can be mapped at a different address in each process. a shared memory segment that is just created is merely a raw chunk of memory. in order to implement the allocation mechanism, we need to store pointers inside this shared memory segment. since the normal pointer stores an absolute address, that address is only valid for the process that placed the object there (unless all processes map the mapped region in the same address). to be able to simulate pointers in mapped regions, we have to create a smart pointer that uses offsets instead of absolute addresses. (this would also be true for user-defined objects that are placed into shared memory; any pointer member must be a smart pointer. and there can be no reference members at all).

the second problem is much simpler to solve; we need to synchronize access …

vijayan121 1,152 Posting Virtuoso
std::string runasc "runas /profile /user:tsc\\staffuser" ;
system( ( runasc + " " + programc ).c_str() ) ;
vijayan121 1,152 Posting Virtuoso

a. gui program: process the WM_QUERYENDSESSION message (with laparam==0)
b. console program: use the SetConsoleCtrlHandler function
c. best: have a windows service running; in the service control handler, (registered with the RegisterServiceCtrlHandlerEx function), handle the SERVICE_CONTROL_PRESHUTDOWN control code.

vijayan121 1,152 Posting Virtuoso

> why is that the only variable that gets the double in the expression itself?
(f-n) and 100 are automatically converted to double by the compiler. you could also write ( double(f - n) / n ) * 100; or ( double(f - n) / double(n) ) * 100.0 ;

vijayan121 1,152 Posting Virtuoso

for XP Professional: from the command prompt execute gpedit.msc
go to: Computer configuration --> windows settings --> scripts (startup/shutdown)
choose Shutdown and add your script/command.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <iostream>

using namespace std;

int main(int, char**) 
{   
    long long n = 6647817899LLU;
    long long f = 10299685494LLU;
    int i = ((f - n) / double(n) ) * 100;
    cout << "Part 4: " << f << " is " << i 
         << "% more than " << n << endl;
    
system("pause");
return 0; }
vijayan121 1,152 Posting Virtuoso

> I heard something that boost's preprocessor library can do that.
> didn't get to try it out : http://boost.org/libs/preprocessor/doc/ref/repeat.html.
BOOST_PP_REPEAT gives a fast horizontal repetition from 0 to N-1
since you need a repetition starting at 1, using BOOST_PP_REPEAT_FROM_TO would be easier.

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <iostream>

#define DEFUN( z, N, arg ) int BOOST_PP_CAT( arg, N )() \
{ return N * N ; }

#define DEFINE_FUNC(N) \
BOOST_PP_REPEAT_FROM_TO( 1, N, DEFUN, square_of_ )

DEFINE_FUNC(15)
 
int main()
{
  std::cout << square_of_11() << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

the major disadvantage of dynamic analysis is that its results may not generalize to future executions. there is no guarantee that the test suite over which the program was run (that is, the set of inputs for which execution of the program was observed) is characteristic of all possible program executions in the future.
the challenge of building a static analysis tool is choosing a good abstraction function, and the challenge of performing effective dynamic analysis is selecting a representative set of test cases. i do not think that one can completely replace the functionality of the other; each one tends to be ill-suited for the tasks at which the other excels.

vijayan121 1,152 Posting Virtuoso

the functions for which you get a linker error are only declared in List.h. they are defined in List.cpp.

the pedantic answer would be: to use templates without their definition being visible, they must be exported. ie. in List.cpp, they must be defined this way:

#include "List.h"
export template<class DataType>
List<DataType>::List()
{
	numItem = 0;
	pHead = 0;
}
// etc

however, most current compilers do not support the export keyword. ( Comeau C++ being the notable exception)

a practical solution would be: move the definitions from List.cpp to List.h (and throw the now empty List.cpp away).

vijayan121 1,152 Posting Virtuoso
// ...
public:
  Form2(void)
  {
      InitializeComponent();
  }
  // ..
protected: 
  virtual void OnActivated( EventArgs^ e ) override
  {
    // clear all strings in combobox
    // reload fresh strings into combobox   
  }
// ...

looks like you need a refresher on basic c++ (and c++/cli) syntax.

vijayan121 1,152 Posting Virtuoso

I have 2 Forms in my Windows Form application. Form1 creates .txtfiles.
I open Form2 from Form1 and can see the .textfiles that is created in a comboBox3.

If I open the application from the beginning and go to Form2 I will see all .txt files that exists in a folder in this comoBox3. While the application is open I close Form2 and is then on Form1 where I now will create a new .text file.
I open Form2 and see if this is in the comboBox3 and it isn´t ?
If I close the whole application, open it again and go to Form2 then it will appear in the comboBox3.
Why do I have to close the application and open it again to receive the changes.

I load in the .txt files to the comboBox3 with this code under Form2(void):

Form2(void)
{
	InitializeComponent();
	//
	//TODO: Add the constructor code here
	//

System::String ^ Files10 = "C:\\Globejennife\\Groupjennif\\"; 
array<System::String ^> ^ files4 = System::IO::Directory::GetFiles(Files10,"*.txt");

array<Char>^ chars = {'.'};
array<System::String ^> ^ splits;
			
    for (int count1 = 0; count1 < files4->Length; count1++)
   {
    splits = files4[count1]->Split(chars);	
    comboBox3->Items->Add(splits[0]->ToString()->Substring(29));

   }
}

override the virtual function OnActivated in Form2. protected: virtual void OnActivated( EventArgs^ e ) ; move the code in the constructor for populating comboBox3 to this function. (and also call the base class OnActivated.) http://msdn2.microsoft.com/en-us/library/system.windows.forms.form.onactivated.aspx

vijayan121 1,152 Posting Virtuoso

> it works. Though not when you use Visual Studio to compile it, then it doesn't work.
you really mean, when you run it from inside Visual Studio.
the reason is that in this case, the current directory of the process is the project directory, not the director(y/ies) where the executable file is located

vijayan121 1,152 Posting Virtuoso

> ... so, what should i change in the coding to solve the problem?
change the return type from void to bool

template < class DataType>
class List
{
    // ...
    bool Traverse(DataType, int &);
    // ...
};
vijayan121 1,152 Posting Virtuoso

> It has to be like this; "CurrentDirectory" + "\\test.jar" or something.
so just use a relative path "test.jar". and put the .exe and the .jar in the same folder.

ProcessStartInfo^ minProssesStartInfo = 
                                   gcnew ProcessStartInfo( "test.jar" ) ;
vijayan121 1,152 Posting Virtuoso

here is a working version which tees the output to en both an edit control and stdout. it's still a toy. real life code would manage an internal buffer (and also handle sync()), would put a cap on the window text size, would be polymorphic on the char_type and traits_type and would have a bunch of typedefs to make usage easy.

#include <iostream>
#include <streambuf>
#include <vector>
#include <cstdio>
#define NO_STRICT
#include <windows.h>

struct my_buff : public std::streambuf
{
    explicit my_buff( HWND w ) : window(w) {}

    protected : 
      virtual int_type overflow( int_type c = traits_type::eof() )
      {
          if( c != traits_type::eof() ) 
          {
              char cc = traits_type::to_char_type(c) ;
              size_t sz = GetWindowTextLength( window ) ;
              std::vector<char> buffer(sz+1) ;
              GetWindowText( window, &buffer.front(), 
                       buffer.size() ) ;
              if( cc == '\n' ) 
              { 
                buffer.back() = '\r' ; 
                buffer.push_back('\n') ; 
              }  
              else buffer.back() = cc ;
              buffer.push_back(0) ;
              if( !SetWindowText( window, &buffer.front() ) ||
                   ( std::putchar(cc) == EOF ) ) 
                      return traits_type::eof() ;
	   }
	  return traits_type::not_eof( c ) ;
	}
  private : HWND window ;
} ;

HWND edit = 0 ;

LRESULT CALLBACK WindowProc(  HWND hw,
                            UINT msg,  WPARAM wp,  LPARAM lp ) 
{
  switch(msg)
  {
    case WM_CREATE :
           edit = CreateWindow( "edit", "",
                    WS_CHILD|ES_MULTILINE|ES_READONLY|WS_VISIBLE, 
                    0, 0, 0, 0, hw, 0, GetModuleHandle(0), 0 ) ;
           SetTimer( hw, 0,  5000, 0 ) ;
           break ;
    case WM_SIZE :
           MoveWindow( edit, 0, 0, LOWORD(lp), HIWORD(lp), TRUE ) ;
           break ;    
    case WM_TIMER :
    {
           static int elapsed = 5 ;
           std::cout << "elapsed: …
vijayan121 1,152 Posting Virtuoso

> How about just forgetting the Get/SetWindowxxx functions and use something like ...
> SendMessage(edit_control, WM_CHAR, achar, 0); yes, when it works it would be a lot more efficient. issues involved include current insertion position (caret) in the control, could text in the control have been selected, is the control read-only etc.

vijayan121 1,152 Posting Virtuoso

well, you need to try for matches for all possible substrings in word.

bool match( const std::string& search_word,
                      const std::string& word )
{
  if( search_word.size()  <= word.size() )
  {
    std::size_t N =  word.size() -  search_word.size() ;

    // pos is the position where the substring starts
    for( std::size_t pos=0 ; pos <= N ; ++pos )
    {
      std::size_t i = 0 ;
      for(  ; i<search_word.size() ; ++i )
      {
        if( ( search_word[i] != '!' ) &&
            ( search_word[i] != word[pos+i] ) ) break ;
      }
      // if the entire search_word has been matched
      if( i == search_word.size() ) return true ;          
    }
  }
  return false ;
}
vijayan121 1,152 Posting Virtuoso

something like this perhaps (it's still only a skeleton and it is not the most efficient):

class edit_control_streambuf : public std::streambuf
{
  public:
    explicit edit_control_streambuf( HWND hedit ) 
          : edit_control(hedit) {}
   // ...
  protected:
    virtual int overflow( int c = traits_type::eof() )
    {
      if ( c != traits_type::eof() )
      {
        char cc = traits_type::to_char_type(c);
        int sz = GetWindowTextLength( edit_control ) ;
        std::vector<char> buffer[sz+1] ;
        GetWindowText( edit_control, &buffer.front(), 
                 buffer.size() ) ;
        buffer.back() = cc ;
        buffer.push_back(0) ;
        SetWindowText( edit_control, &buffer.front() ) ;
      }
      return traits_type::not_eof( c ) ;
     }
     // ...
  private:
    HWND edit_control ;
} ;
vijayan121 1,152 Posting Virtuoso

the simplest way would be to use a streambuf that outputs to the control
the skeleton would be:

#include <streambuf>

class textbox_streambuf : public std::streambuf
{
   // ...
  protected:
    virtual int overflow( int c = traits_type::eof() )
    {
      if ( c != traits_type::eof() )
      {
        char cc = traits_type::to_char_type(c);
        // do whatever is required send cc to text box 
        // or control you want to use.
        // if( successfull )
          return traits_type::not_eof( c ) ;
        // else
          return traits_type::eof() ;
       }
       return traits_type::not_eof( c ) ;
    }
    // ...
  private:
    // ...
} ;

int main()
{
  textbox_streambuf tbsbuf( /* ... */ ) ;
  std::streambuf* old = std::cout.rdbuf( &tbsbuf ) ;
  // ...
  // before tbsbuf is destroyed:
  std::cout.rdbuf( old ) ;
}
vijayan121 1,152 Posting Virtuoso

The definition void main() { /* ... */ } is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. A conforming implementation accepts int main() { /* ... */ } and int main(int argc, char* argv[]) { /* ... */ } A conforming implementation may provide more versions of main(), but they must all have return type int.

The int returned by main() is a way for a program to return a value to "the system" that invokes it. On systems that doesn't provide such a facility the return value is ignored, but that doesn't make "void main()" legal C++ or legal C. Even if your compiler accepts "void main()" avoid it, or risk being considered ignorant by C and C++ programmers.

vijayan121 1,152 Posting Virtuoso
// search_word is one word from the search_words array
// word is one word from the words array
// equals returns true if there is a match, false otherwise
bool equals( const std::string& search_word, 
             const std::string& word )
{
  if( search_word.size() == word.size() )
  {
    // test char by char for all the chars
    for( std::size_t i=0 ; i<search_word.size() ; ++i )
    {
      if( ( search_word[i] != '!' ) &&
          // if any char (which is not '!' ) in the search_word 
          // is different from the corrosponding char in word
          // there is no match; return false
          ( search_word[i] != word[i] ) ) return false ;
    }
    // if every character (other than !) in search_word
    // matches the corrosponding char in word and
    // both have the same number of chars, there is a match
    return true ;
  }
  else return false ; // different sizes, no match
}
vijayan121 1,152 Posting Virtuoso

> since I only defined function() once.
you defined it twice. once in a.cpp and once in main.cpp (which includes a.cpp)

vijayan121 1,152 Posting Virtuoso

> my program is able to count every time one word from the search_word array is in the words array.
> Some of the search_words; however, have exclamation points in them...

use the same logic, but while comparing strings, make sure that an '!' in the search_word matches any char in the corrospong position in the word.

bool equals( const std::string& search_word,
             const std::string& word )
{
  if( search_word.size() == word.size() )
  {
    for( std::size_t i=0 ; i<search_word.size() ; ++i )
    {
      if( ( search_word[i] != '!' ) &&
          ( search_word[i] != word[i] ) ) return false ;
    }
    return true ;          
  }
  else return false ;
}
vijayan121 1,152 Posting Virtuoso
#include <string>
#include <algorithm>
#include <iostream>
using namespace std ;

int main()
{
  string MyString = "The rabbit likes to ea! carro!s";
  cout << MyString << '\n' ;
  replace_copy( MyString.begin(), MyString.end(), 
                MyString.begin(), '!', 't' ) ;
  cout << MyString << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> The data is basically alot of text and integer values.
> It needs to be accessed, sorted and filtered
> Not much data will be added maximum size will go to 400K

just use a simple xml file to store the data.
and an xml parser library eg. http://www.grinninglizard.com/tinyxml/

vijayan121 1,152 Posting Virtuoso

> Anyone been there, done that?
no, i haven't done anything of the kind. but i do know that the *bsd unixes do provide (sometimes limited) binary emulation for a variety of operating systems. i think NetBSD would be the best option for attempting this. the part of the kernel source tree you would want to look at is /usr/src/sys/compat/svr4. compat_svr4 provides binary compatibility for several systems, SCO/Xenix on i386 among others.

information on the NetBSD kernel source tree http://ezine.daemonnews.org/200205/netbsdsrctree3.html

binary emulation http://www.netbsd.org/docs/compat.html
http://www.netbsd.org/docs/compat.html#ports

compat_svr4 man page http://netbsd.gw.com/cgi-bin/man-cgi?compat_svr4++NetBSD-current
all the best.

vijayan121 1,152 Posting Virtuoso

the exception thrown is of type float, not int
you have to catch it as a float. catch( float nValue ) { /* ... */ }

vijayan121 1,152 Posting Virtuoso
array<System::String ^> ^ files4 = System::IO::Directory::GetFiles(Files,"*.txt");
if( files4->Length > 0 )
{
  System::String ^ text =  files4[0] ;
  for( int i = 1 ; i < files4.Length ; ++i )
      text += System::Environment::NewLine + files4[i] ;
  this->textBox1->Multiline = true ; // if not multiline
  this->textBox1->WordWrap = false ; // if required
  this->textBox1->Text = text ;
}
vijayan121 1,152 Posting Virtuoso

> What is missing in my code ?
the Text property of the ListControl is a System::String.
(it represents the currently selected string of the list control).
the variable file4 is an array of System::String ie. cli::array< System::String ^ > ^
if you want to set the selected string into the first element of this array, you could write

if( file4.Length > 0 )
     this->textBox1->Text = files4[0] ;
vijayan121 1,152 Posting Virtuoso

> how do i make the final calculation become 41.6 ?

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
  std::cout << 374.0 / 9.0 << '\n' ;
  std::cout << std::fixed << std::setprecision(1) 
            << 374.0 / 9.0 << '\n' ;
  
  std::stringstream stm ; 
  stm << std::fixed << std::setprecision(1) 
      << 374.0 / 9.0 << '\n' ;
  stm.seekg( 0, std::ios::beg ) ;
  double result ;
  stm >> result ;
  std::cout << result << '\n' ;
  // *note* result == ( 41.6 += epsilon )
  // http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16
  // http://en.wikipedia.org/wiki/Floating_point
}
vijayan121 1,152 Posting Virtuoso

> I have: Directory::GetFiles(Files,"*.txt");
> Files is in a format: cli::array<Type,dimension> ^
> How could Files be converted to System::string ^

presumably, the Type in cli::array<Type,dimension> is wchar_t and the dimension is 1.
all cli array types derive from System::Array and you could directly use the constructor of a System::String that accepts a Char[] . http://msdn2.microsoft.com/en-us/library/ttyxaek9.aspx

alternatively, you could use the static array<String^>^ GetFiles( String^ path ) http://msdn2.microsoft.com/en-us/library/07wt70x2.aspx which will return an array of *all* files in the directory. you could then test each file name to see if it ends in ".txt" by using bool System::String::EndsWith( System::String^ ) http://msdn2.microsoft.com/en-us/library/2333wewz.aspx

vijayan121 1,152 Posting Virtuoso

> I have seen some code where some variable gets inserted into string through the % sign
the code you saw was probably using the Boost.Format library to insert stuff into a stringstream. http://www.boost.org/libs/format/doc/format.html

vijayan121 1,152 Posting Virtuoso
// .NET Framework 2.0 or higher

LPSTR to_LPSTR( System::String^ s, char buffer[], std::size_t sz  )
{
   using namespace Runtime::InteropServices ;
   void* temp = Marshal::StringToHGlobalAnsi(s).ToPointer() ;
   errno_t result = strcpy_s( buffer, sz, (const char*)temp ) ;
   Marshal::FreeHGlobal( IntPtr( temp ) );
   return result==0 ? buffer : 0 ;
}

System:String^ files8 = folderBrowserDialog1->SelectedPath->ToString();
char buffer[ MAX_PATH ] ;
LPCSTR pcstr = to_LPSTR( files8, buffer, sizeof(buffer) ) ;
vijayan121 1,152 Posting Virtuoso

> I'm wondering if there is a more elegant solution.
perhaps use a parser framework like boost.spirit http://www.boost.org/libs/spirit/index.html

vijayan121 1,152 Posting Virtuoso

> Does this mean that things like toolbars would come under the Model or the View
in general, *all* user interface elements (toolbars,statusbars,menu etc) would be part of the 'view'.

> I was also wondering if storing all the drawing could be nicely done using XML?
yes, that is the modern approach. (and the persistence/data access layer is encapsulated by the 'model'.)

vijayan121 1,152 Posting Virtuoso

a commonly used architecture is http://en.wikipedia.org/wiki/Model-view-controller

> Right now, I'm thinking along the lines of having two main objects, a Screen and a Handler
these roughly correspond to view and controller
lines, circles etc. would be part of the model.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

or use a union

int main()
{
   typedef unsigned char byte ;
   union
   {
     byte buffer[ sizeof(long) ] ;
     long key ;
   };
   // ...
}
SpS commented: Nice +4
vijayan121 1,152 Posting Virtuoso

write a function to covert a text file to an xml file.
have two nested loops; the outer one to iterate over the folders, and the inner one to iterate over files in that folder.

#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>

void convert_to_xml( std::istream& in_file, 
                     std::ostream& out_file )
{
   // convert it
}

int main()
{
  struct folder_info { const char* name ; int num_files ; };
  const folder_info folders[] = 
  { 
     { "/usr/home/me/folder_1", 58 }, 
     { "/usr/home/me/folder_2", 41 },
     /* etc */ 
  }; 
  enum { NFOLDERS = sizeof(folders) / sizeof( folders[0] ) };

  const std::string file_name_prefix = "filename-" ;
  const std::string in_file_name_suffix = ".txt" ;
  const std::string out_file_name_suffix = ".xml" ;
  const char seperator ='/' ; 
  
  for( int i=0 ; i<NFOLDERS ; ++i )
    for( int j=0 ; j<folders[i].num_files ; ++j )
  {
     std::ostringstream in_file_name, out_file_name ;
     in_file_name << "folders[i].name" << seperator 
                  << file_name_prefix << std::setw(2) 
                  << std::setfill('0') << j+1 
                  << in_file_name_suffix ;
     out_file_name << "folders[i].name" << seperator 
                   << file_name_prefix << std::setw(2) 
                   << std::setfill('0') << j+1 
                   << out_file_name_suffix ;
     std::ifstream in_file( in_file_name.str().c_str() ) ;
     std::ofstream out_file( out_file_name.str().c_str() ) ;
     if( in_file && out_file ) 
        convert_to_xml( in_file, out_file ) ;
     // else error
  }
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> the following piece of simple code(it didn't work in any of the compilers VC++,GCC etc)
the code is incorrect and should not compile without an error. this is (a simplified version) of what the standard says about while loops:

in while(condition) substatement the condition is one of
i. expression
ii. type-specifier-seq declarator = assignment-expression

the declarator shall not specify a function or an array. the type-specifier-seq shall not contain typedef and shall not declare a new class or enumeration.

the value of a condition that is an expression is the value of the expression, implicitly converted to bool; if that conversion is ill-formed, the program is ill-formed.
the value of a condition that is an initialized declaration is the value of the declared variable implicitly converted to bool; if that conversion is ill-formed, the program is ill-formed.

if a condition can be syntactically resolved as either an expression or the declaration of a local name, it is interpreted as a declaration.

The object created in a condition is destroyed and created with each iteration of the loop.
Example:

struct A 
{
    int val;
    A(int i) : val(i) {}
    ~A() {}
    operator bool() { return val != 0; }
};
int i = 1 ;
while( A a = i ) { /* ... */ i = 0 ; }

in the while-loop, the constructor and destructor are each called twice, once for the condition that succeeds and once for the condition that fails.

the …

vijayan121 1,152 Posting Virtuoso
template<typename DataType>
class Value
{
   // ...
   Value& operator +(const Value& aValue);
   // ..
};
template<typename DataType>
Value<DataType>& Value<DataType>::operator +(const Value<DataType>& aValue)
{ /* ... */ }

this operator+() only allows two Value template instantiations for the same DataType to be used. ie. you could add a Value<int> to another Value<int>, but not a Value<int> to a Value<short>.

also, the operator+ is not const-correct and tries to return a reference to an anonymous temporary.

perhaps this is what you intended

template<typename DataType>
class Value
{
public:
  Value(DataType val);
  // ...
  template< typename other >
  Value<DataType> operator+ ( const Value<other>& that ) const
  { return Value<DataType>( _value + that.GetValue() ); }
  // ...
  const DataType& GetValue() const { return _value; }
  //...
 protected:
  DataType _value;
};
vijayan121 1,152 Posting Virtuoso

> For some reason reference to operator() bothers me. Am I missing something simple?
one reason why this may be a bother is possible loss of efficiency. a function called via a pointer is usually not inlinable. (what a pointer points to is techically something that is known only at runtime.) perhaps this is a simpler option:

template< typename FN > struct call_it
{
  typename FN::result_type operator()( const FN& fn ) const
  { return fn() ; }
};

int main()
{
  typedef boost::function< void(void) > fn_t ;
  std::vector< fn_t > functions ;
  // ..
  std::for_each( functions.begin(), functions.end(),
                 call_it<fn_t>() ) ;
}
vijayan121 1,152 Posting Virtuoso

The ISO/ANSI C function is double pow( double, double ) ; C++98 functions are:

float std::pow( float, float ) ;
float std::pow ( float, int ) ;
double std::pow( double, double ) ;
double std::pow( double, int ) ;
long double std::pow( long double, long double ) ;
long double std::pow( long double, int ) ;

C++0X adds:

there shall be additional overloads sufficient to ensure that:
1. If any argument corresponding to a double parameter has type long double, then all rguments corresponding to double parameters are effectively cast to long double.
2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.
3. Otherwise, all arguments corresponding to double parameters are effectively cast to float.

so these ambiguities would go away with C++0X

vijayan121 1,152 Posting Virtuoso

> charread.read() failed as soon as I added the code to open the same file
> for the output stream (charfile). Something is wrecking the input stream,
> and besides that the presence of the output stream is causing it charfile.open("character.dat",ios::binary|ios::out); is truncating the stream to zero size (default while opening only for output).

void initializeslots(character* dummy)
{
	character* charbuf;
	charbuf = new character;
	ifstream charread;
	fstream charfile;

	charread.open("character.dat",ios::binary|ios::in);
	if(charread.fail())
	{
		cerr << "Failed to open character.dat for reading!" << endl;
		return;
	}
	charfile.open("character.dat",ios::binary);
        // ...

should fix it.

vijayan121 1,152 Posting Virtuoso

your compiler may require c = std::pow( a, b ) ; . this is correct as you are using <cmath> (not math.h)
the more likely reason is that the function pow is overloaded in c++

double pow ( double base, double exponent );
long double pow ( long double base, long double exponent );
float pow ( float base, float exponent );

and pow(a,b) results in an ambiguous call to overloaded function. c = std::pow( double(a), b ) ; . should remove the ambiguity.

vijayan121 1,152 Posting Virtuoso

> Now I want to put the items that were searched for into the front of the multimap.
this is not possible (unless you perform tricks with the key). maps and multimaps are associative containers; they associate keys and values. fast lookup on the key what they are designed for.
you could use a simple sequence container like std::list< std::pair< int, std::string > > if you want to determine the order in the sequence arbitrarily.