C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.

Share tech news, updates, or what's on your mind.

Sign up to Post

Ref: https://www.experts-exchange.com/questions/29138856/Unable-to-Run-Program-Using-a-Pointer-to-a-Template-Method-Inside-a-Template-Class.html

I tried to extend the referenced example by trying to pass a Pointer to Member function into a template. I am doing this because I have another application that has a template function, and I would like to pass a Pointer To Member construct into it. The below program builds and runs, but the pass_PtrToMember_Into_Function function is not invoked. When I modify the call to handle a warning, I get error messages shown below.
#include <iostream>

template<typename TYPE>
class Target5
{
public:
	Target5(const TYPE &value) : value(value) {}
	TYPE value;

	template <typename T>
	int OneParam(T a)
	{
		std::cout << "\nTarget5::OneParam(" << value << "," << a << ")\n";

		typedef void (Target5<TYPE>::*MethodTypeToCall)(T);
		MethodTypeToCall toCall = &Target5<TYPE>::Private;  // Here, the compiler picks the right overload

		auto toCall2 = &Target5<TYPE>::Private<T>;  // this alternative works OK
		(this->*toCall)(a);
		(this->*toCall2)(a);

		return 1;
	}

	template <typename T1, typename T2>
	int TwoParam(T1 a, T2 b)
	{
		std::cout << "\nTarget5::TwoParam(" << value << "," << a << "," << b << ")\n";

		auto toCall2 = &Target5<TYPE>::Private<T1, T2>;
		(this->*toCall2)(a, b);

		return 2;
	}

private:
	template <typename T>
	void Private(T a)
	{
		std::cout << "Target5::Private(" << value << "," << a << ")\n";
	}
	template 

Open in new window

0
OWASP: Forgery and Phishing
LVL 13
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Ref: https://goodliffe.blogspot.com/2011/07/c-declaring-pointer-to-template-method.html
Seems like others don't have the issues I am encoutering with this blog, but I have been unable to build/run case 5. I added this simple main() function:
int main()
{
	PointerToNormalMemberFunction(); // target 1
	PointerToTemplateMemberFunction(); // target 2
	PointerToTemplateMemberFunctionWithTwoParameters(); // terget 3
	PointerToTemplateMemberInTemplateClass(); // target 4
//	HoldingAPointerToTemplateMemberInTemplateClass(); // target 5 ---> Had to comment this out
}

Open in new window

In the referenced link are five cases. I am having trouble with case 5. Here is the code for this last case. Can you get a simple test program to work with this case 5? Thanks!
#pragma once

#include <iostream>

template<typename TYPE>
class Target5
{
public:
	Target5(const TYPE &value) : value(value) {}
	TYPE value;

	template <typename T>
	void OneParam(T a)
	{
		std::cout << "Target5::OneParam(" << value << "," << a << ")\n";

		typedef void (Target5<E>::*MethodTypeToCall)(T);
		// Here, the compiler picks the right overload
		MethodTypeToCall toCall = &Target5<E>::Private;
		// In this case, the compiler does not let us write the following line (parse error):
		//MethodTypeToCall toCall = &Target5<E>::Private<t;;
		(this->*toCall)(a);
	}

	template <typename T1, typename T2>
	void TwoParam(T1 a, T2 b)
	{
		std::cout << "Target5::TwoParam(" << value << "," << a << "," << b << ")\n";

		typedef 

Open in new window

0
Hello

How can i pass an argument to a visual studio .exe (C++ project) from the command line i.e. cygwin?

Please note that I do not want to pass the argument via the Visual Studio GUI under debugger->Command Arguments.

So I would like something like this:
cygwin>a.exe 4

thanks
0
Problem with visual 6 C++ code converting to visual studio 2010 c++. The following is the only code that errors out. The rest of the lib converts and compiles fine if I remark out this one line of code.
      WCHAR *printable = new WCHAR[(dwBufferSize+1)*2];
      printable[0] = '\0';

      for (unsigned long i =0;i<dwBufferSize;i++)
      {
         WCHAR scratch[3];
		 wsprintf(scratch,L"%02X", pBuffer[i]);   //This is the problem code. wsprintf requires LPSTR but scratch is WCHAR
         wcscat(printable, scratch);
      }

      *pbstrEncrypted = SysAllocStringLen(printable, dwBufferSize*2);

I've looked for code on the internet to convert a variable from WCHAR to LPSTR and back again. I could make do with that.  As near as I can see the wsprintf with the format 
code %02X takes a single wide char and makes it two hex output characters and concatenates it to the printable variable. This code was written in 2000.

Bob


      delete [] printable;

Open in new window

0
Hi all,

  I do want to store  "directory path" as a  key and corresponding value as a value. The key would be 1024.

  If I take std::map, I guess it would be performance hit with huge number of entries.

  It has to maintain this ds inside kernel module. What is the best ds to implement this in C++ 11?

Thanks,
Bvm.
0
With Lilypad e-textiles do you have to pair an Arduino board (nano or uno) with it or are these programmable themselves with Arduino software.  I have multiple LilyPad Arduino Simple Snaps and would like to program them to allow a student to push a button and have led lights go off in succession.
We are attempting to make interactive maps like what you would see in a museum.  Button goes off and the lights light up an army path or the outline of a state.
0
I have implemented a string-like class, called Str, and want to add a conversion to bool type, in order to use a Str object as a condition. The Str class is quite simple and relies on the STL vector class. Everything works fine, except that now, if I try for example to do the following:

Str greeting = "Hello, " + name + "!";

Open in new window

where "name" is a Str, then I get a compilation error, saying "'operator +': 2 overloads have similar conversions, could be 'Str operator +(const Str &,const Str &)' or 'built-in C++ operator+(const char [8], int)'.

I understand the reason for the error, but I am not sure how to fix it. How can I get around this? Below I have copied a minimal working example.

#include <iterator>
#include <vector>
#include<iostream>

using namespace std;

class Str
{

private:
    std::vector<char> data;

public:
    typedef std::vector<char>::size_type size_type;
    typedef std::vector<char>::iterator iterator;
    typedef std::vector<char>::const_iterator const_iterator;

    iterator begin() { return data.begin(); }
    const_iterator begin() const { return data.begin(); }
    iterator end() { return data.end(); }
    const_iterator end() const { return data.end(); }


    // default constructor must be defined explicitly, since non-default constructors are also defined
    Str() { }
    Str(const size_type n, const char c) : data(n, c) {  }
    Str(const char* cp)
    {
        std::copy(cp, cp + std::strlen(cp), std::back_inserter(data));

Open in new window

0
I am using zlib 1.2.7 zlibstat.lib with a Visual Studio 2015 MFC application. When I include this library I get warning messages:

zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol __stdio_common_vsprintf imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally defined symbol __stdio_common_vsprintf imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol free imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally defined symbol free imported
zlibstatic.lib(zutil.obj) : warning LNK4049: locally defined symbol free imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol malloc imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally defined symbol malloc imported
zlibstatic.lib(zutil.obj) : warning LNK4049: locally defined symbol malloc imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol wcstombs imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol _wopen imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol _lseeki64 imported
zlibstatic.lib(gzlib.obj) : warning LNK4049: locally defined symbol open imported
OLDNAMES.lib(open.obi) : warning LNK4049: locally defined symbol open imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally defined symbol _errno imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally defined symbol strerror imported
zlibstatic.lib(gzwrite.obj) : warning LNK4049: locally…
0
I am trying to customize a print dialog in a MFC app.
I want the "pages" option to be preselected.

In CMyView::OnPreparePrinting(CPrintInfo* pInfo)
I added this at the end of the function:
      pInfo->SetMinPage(10);
      pInfo->SetMaxPage(20);
      pInfo->m_pPD->m_pd.nFromPage = 10;
      pInfo->m_pPD->m_pd.nToPage = 20;
      pInfo->m_pPD->m_nFlags |= PD_PAGENUMS;
      return DoPreparePrinting(pInfo);

When the print dialog comes up, the "all" option is preselected.
0
I'm trying to run a very simple Hello World program on a Linux workstation.  The code compiles, but when I double-click on the .exe file to run it, a window pops up with the message "An Error Occurred While Loading the Archive".  

I've attached the code and Makefile below.

What am I doing wrong?

Thanks!

#include <iostream>
using namespace std;
//hello.cpp

int main()
{
  cout << 'Hello world!\n';
  return 0;
}

Open in new window



TARGET	= hello.exe
OBJECT_01	= hello.o
SOURCE_01	= hello.cpp

$(TARGET): $(OBJECT_01)
	gcc -o $(TARGET) $(OBJECT_01) -lstdc++

$(OBJECT_01): $(SOURCE_01)
	gcc -c $(SOURCE_01) -o $(OBJECT_01)

all: $(TARGET)

clean:
	-rm -f $(TARGET) 
	-rm -f $(OBJECT_01)

Open in new window

0
Starting with Angular 5
LVL 13
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Hi,
I am facing an issue regarding unicode text.
In a ATL dll project I am using LDAP to get data from Active Directory. Following is the sample code.  

IDirectorySearch *pDSSearch;
ADS_SEARCH_COLUMN col;
hr = pDSSearch->SetSearchPreference(rgSearchPrefs, ARRAYSIZE(rgSearchPrefs));
hr = pDSSearch->ExecuteSearch(strFilter, pszAttr ,dwAttrNameSize, &hSearch );

if(SUCCEEDED(hr))
	{						
		switch(col.dwADsType)
		{ 
			case  ADSTYPE_DN_STRING:
			case ADSTYPE_CASE_IGNORE_STRING:
				{			
					for(size_t x=0; x<col.dwNumValues;x++)
					{
						CString name = col.pADsValues[x].CaseIgnoreString; //fails for unicode text
					}
				}
		}
	}

Open in new window


The line CString name = col.pADsValues[x].CaseIgnoreString; works fine for English text, but returns '???' for other languages. For example if the Active directory contains any user's name in Chinese or Japanese text '邮箱' then CString name shows '???' instead of the actual unicode text.
The same code works properly in another MFC Application project but fails for this ATL dll project.

Project settings are :
Configuration Type : Dynamic Library(.dll)
Use of MFC :      Use MFC in a Static Library
Use of ATL :       Static Link to ATL
Character Set :  Use Unicode Character Set

Cannot trace what I have been missing out. Please help.
0
I have multiple instances of Microsoft Visual C++. Do I need them all?

Capture.JPG
0
Code returning error message.  Unsure how to fix.

exit status 1
main.cpp:19:1: error: expected unqualified-id before '{' token
 {


Here's the code:

#include <iostream>
#include <iomanip>
using namespace std;
const int arrsize = 9;
int main()
{
int i = 0;
int j = 0;
int matrix[3][3];
cout<<" please enter 9 digits "<<endl;
for (int i = 0; i < 3; i++)
{
  for (int j = 0; j < 3; j++)
  {
    cin>>matrix[i][j];
  }
}
}
{
for (int i = 0; i < 3; i++)
{
  for (int j = 0; j < 3; j++)
  {
    cout>>matrix[i][j];
  }
  cout<<endl;
}
}
0
Is it possible to create a cross-platform desktop application in Visual Studio 2017 that will run in both Windows 10 and Linux environments (how is it done)?  
I don't see any "New Project" options that stand out, nor much information on the web.

Thanks
1
Hi I have a 2D vector in a library which gets populated with different types of data this part is working fine now I need to pass the 2D vector back to my main app from a function call but this function call is failing

Here is the structure that makes up the vector in the library and how I am trying to call the data in the vector from a function:
//Library code
typedef struct _DEVICEDETAILS
{
	std::string IPaddr;
	int HTTPPort;
	int HTTPSPort;
	int RTPSPort;
	std::string Model;
	std::string Name;
	std::string token;
	std::vector<std::string> RSTPURL;
	std::vector<char*> data;
	std::vector<size_t> datalen;
	std::string _mediaXaddr;
	int Encoding;
	int Width;
	int Height;
	int Quality;
	int FrameRateLimit;
	int EncodingInterval;
	int Bitrate;

}DEVICEDETAILS;

struct ONVIFDEVICE
{
	std::string MacAddr;
	std::vector<DEVICEDETAILS> _videotype;
};

ONVIFDEVICE m_MacAddr;
std::vector<std::vector<ONVIFDEVICE>> v_Device;

void GetOvifInfo(std::vector<std::vector<ONVIFDEVICE>> &returnInfo)
{
  other code .......
   int m_size =v_Device.size();
   v_Device.resize(m_size+1);
   v_Device[nFindDev].push_back(m_Mac); // info gets populated into each element here
   nFindDev++;
   
  //Need to do a deep copy from vector v_Device to  vector returnInfo

}

// Main App code
typedef struct _mDEVICEDETAILS
{
	std::string IPaddr;
	int HTTPPort;
	int HTTPSPort;
	int RTPSPort;
	std::string Model;
	std::string Name;
	std::string token;
	std::vector<std::string> RSTPURL;
	std::vector<char*>

Open in new window

0
I have following version of eclipse IDE installed in my computer:
Eclipse IDE for C/C++ Developers
Version: 2018-09 (4.9.0)

I created a workspace.  There are number of Templates for New C / C++ Project.
I need to import very large 'C' source code files into my project.  I won't be compiling code in eclipse.  I'll just be navigating source code.
Which Project template should I select?  Is there a way to create project without selecting a project template?
0
Yellow rect is the window it's moved from left to rightI am implementing a draggable window and in my mousemove i am setting it's position using MoveWindow() API but problem is while it is moving it is leaving its trace behind i have attached the image The place where it was present earlier is not getting erased, i have used OnEraseBackground to true and false
0
I'm trying to investigate a problem with resource files generated by Google Omaha. These resource files contain a place-holder token (%1!s!), which is substituted with branding details during the build process. There are numerous language resource files that contains string tables and this

Here is an example string: "%1!s! some arbitrary text"

Where %1!s! is a place-holder for some substitution text?

My question: is this place-holder substitution mechanism a standard part of the Windows resource file mechanism? If so, can someone please either explain how it works? Where does it get the text used to substitute the place holder? I'm assuming the place-holder works similar to place-holders in printf? If so, how does it know which text token to replace this with? If this is not a standard resource file mechanism, does anyone have a clue as to how Omaha does this during the build process?

Many thanks.

Note: I'm not looking for suggestions to use a different approach. This is how Omaha does it and I just need to understand how this works. Thank you.
0
Hey!

I am developing an application using JetBrains CLion 2018.2.4 with cmake 3.12.2 and Visual Studio 2017 compiler.
Let me set up things first.

Here is the base class:
class Header
{
public:
   enum MessageType
   {
      Message = 100,
      Command = 101,
      InvalidMessage = 102
   };

   Header();
   Header(Header::MessageType messageType);
   virtual ~Header() = default;

   Header::MessageType GetMessageType() const;
private:
   Header::MessageType m_messageType;
};

Header::Header() :
   m_messageType(Header::MessageType::InvalidMessage)
{
}

Header::Header(Header::MessageType messageType) :
   m_messageType(messageType)
{
}

Header::MessageType Header::GetMessageType() const
{
   return m_messageType;
}

Open in new window


Here is the derived class:
class Message : public Header
{
public:
   Message();
   ~Message() = default;

   void SetMessage(std::string message);
   std::string GetMessage() const&;

private:
   std::string m_message;
};

Message::Message() :
   Header(Header::MessageType::Message),
   m_message("")
{
}

void Message::SetMessage(std::string message)
{
   m_message = message;
}

std::string Message::GetMessage() const&
{
   return m_message;
}

Open in new window


Here is how I'm acessing the function GetMessage();
int main()
{
   Reader reader;

   auto basePtr = reader.ReadAll(message);
   auto derivedPtr = std::dynamic_pointer_cast<communication::Message>(basePtr);
   std::cout << "read: " << derivedPtr->GetMessageType() << ";" << derivedPtr->GetMessage();
}

Open in new window


When I try to execute GetMessage() like up above, I get the error below:

Server.cpp.obj : error LNK2019: unresolved external symbol "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall communication::Message::GetMessageA(void)const & " (?GetMessageA@Message@communication@@QGBE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function _main
Server.exe : fatal error LNK1120: 1 unresolved externals

Open in new window


It has to do with the function GetMessage() but I'm failing to see what is wrong. If I remove that call, everything compile fine.
Also, I do the exact same call in other class and it is working fine.
Help is needed!!!
0
PMI ACP® Project Management
LVL 13
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

dup2(int oldfd, int newfd);

Open in new window


This is an equivalent of:

close(int newfd);
dup(int oldfd);

Open in new window


By closing "newfd" first, it becomes the lowest-numbered unused file descriptor (normally). Because of that the oldfd is copied to newfd (dup system call). So far, everything is clear.

Now see: http://codewiki.wikidot.com/c:system-calls:dup2


dup2 is a system call similar to dup in that it duplicates one file descriptor, making them aliases, and then deleting the old file descriptor.

Actually I don't think the old file descriptor will be deleted?

See: http://man7.org/linux/man-pages/man2/dup.2.html

After a successful return, the old and new file descriptors may be used interchangeably.

If the old file descriptor will be deleted, then they would not say something like that. Is wikidot.com just wrong about this?
0
I'm trying to understand the structure of the open file table. During this search I'm reading things that look like (for me) they are in contrast with each other.

In a system there is a:

File descriptor table:
This table is located in user space and is associated with a certain process (per-process).

Open file table:
This table is located in kernel space and is associated with all processes (process-wide).

Entries in the file descriptor table point to the open file table. This all is clear. Now let's go to the structure of these tables. For example, see: https://elixir.bootlin.com/linux/v3.18/source/include/linux/fdtable.h#L24

struct fdtable {
        [...]
};

Open in new window


And:

/*
 * Open file table structure
 */
struct files_struct {
        [...]
};

Open in new window


Also this is clear. But now see for example: http://www.andrew.cmu.edu/user/gkesden/ucsd/classes/sp17/cse291-a/applications/ln/lecture5.html

Per Process File Information


struct files_struct { /* kept within task_struct (PCB) */
        [...]
};

Here they are talking about files_struct when it's about "per process file information". I don't understand this, because the open file table is process-wide. This is for example what they are saying:

The count variable tracks the number of files the process has open

But imagine ... two different processes point to the same entry in the open file table. I think …
0
Dear experts,

I am learning C++

I have some idea about Objects in C++

Is there an online course which can teach me 'objects' and ' Data Structures' in great detail?

Kindly suggest.
0
I am considering using a Rasberry Pi as an SBC (single board computer) with Android O/S installed and programming with Embarcadero RAD Studio 10.2  (C++ builder). Is there a library or other means of using the GPIO of the Rasberry Pi and other hardware features of the SBC ?
0
Question is related to C++ STL list::sort(Compare) where Compare is now a template.

I am looking for the correct syntax to override the list::sort(Compare) definition to work with list<pair<int, T> > definition.

//-The Compare Function

template<typename W>
bool weightsort(const pair<int, W> &node1, const pair<int, W> &node2)
{
    return (node1.second <= node2.second);
}


//- Abbreviated class definition containing  STL list definition and call to sort

template<typename T>
class Graph {
    ...
    vector<T> shortest_reach(int startId, T sigWeight) {
        ...
        list<pair<int, T> >                                       frontier;   //-Nodes currently on the Queue to be Explored.
        typename list<pair<int, T> >::iterator      fit;
        ...
            frontier.sort(weightsort);
        ...
    }
    ....
};


$ c++ program.cpp

error: no matching member function for call to 'sort'
            frontier.sort(weightsort);
            ~~~~~~~~~^~~~

usr/include/c++/v1/list:1059:14: note: candidate template ignored:
      couldn't infer template argument '_Comp'
        void sort(_Comp __comp);
             ^
/usr/include/c++/v1/list:1056:10: note: candidate function not viable:
      requires 0 arguments, but 1 was provided
    void sort();
         ^
0
Dear experts,

In the recent past I have been inquiring or seeking your expert guidance on pursuing a career in Financial Engineering.
I have now reached the stage of working on objects in C++. Once I am thorough with C++ and after having worked on ‘Introduction to C++ for Financial Engineers’ by Daniel J Duffy, I plan to do a project work.
This project work will be done by me while I am in leave.
Can I request if anyone can guide me on selecting a project on Python/C++?
Which platform will be robust for this purpose?
Is there a book I can purchase and practice? Can I use the knowledge I gain by practicing this book in my interview process?

Kindly guide me.
0

C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.