Home > c# > boost::shared_ptr does not have a class type

boost::shared_ptr does not have a class type

March 13Hits:1
Advertisement

I have implemented a tcp client and tcp server using boost asio. The code is given below. (test.cpp, test.hpp and makefile)

The executable can be run as

(server side)

$ ./client_server 1 5005 

(client side)

$ ./client_server 0 5005 

tcp_sever uses a holder class tcp_connection for each clients that connects to the server.I have added a std::vector of type inside tcp_connection class (added in the code below).

std::vector<pointer> m_subscribers; 

I want to populate this vector either inside static pointer create(boost::asio::io_service& io_service); of class tcp_connection

OR inside

tcp_server::start_accept() after the connection has been created.

To access the private member variable m_subscribers from tcp_server I need to implement an accessor function.

std::vector<tcp_connection::pointer> &tcp_connection::get_subscriber_list() {       return m_subscribers; } 

and inside tcp_server::start_accept I do

new_connection->get_subscriber_list.insert(new_connection);

I get the error error: ‘new_connection.boost::shared_ptr<T>::operator-><tcp_connection>()->tcp_connection::get_subscriber_list’ does not have class type

test.cpp

#include "test.hpp" #include <iostream> #include <exception> #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <algorithm> #include <sstream> #include <iomanip>  const int ARG_COUNT = 2; const int MAX_PACKETS = 25; const int LOWEST_PORT = 1024; const int HIGHEST_PORT = 65000;  static char message_array[8192];  void gen_random_string(char *s, const int len) {     static const char alphanum[] =         "0123456789"         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"         "abcdefghijklmnopqrstuvwxyz";      for (int i = 0; i < len; ++i) {         s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];     }     s[len] = 0; }  class tcp_connection :public boost::enable_shared_from_this<tcp_connection> { public:     typedef boost::shared_ptr<tcp_connection> pointer;      static pointer create(boost::asio::io_service& io_service)     {         return pointer(new tcp_connection(io_service));     }      boost::asio::ip::tcp::tcp::socket& socket()     {         return socket_;     }      void start()     {         gen_random_string(message_array, 8192);         std::string message(message_array);          boost::asio::async_write(socket_, boost::asio::buffer(message),                                  boost::bind(&tcp_connection::handle_write, shared_from_this(),                                              boost::asio::placeholders::error,                                              boost::asio::placeholders::bytes_transferred));     }  private:     tcp_connection(boost::asio::io_service& io_service)         : socket_(io_service)     {     }      void handle_write(const boost::system::error_code& /*error*/,                       size_t /*bytes_transferred*/)     {     }      boost::asio::ip::tcp::socket socket_;     std::vector<pointer> m_subscribe;     std::string message; };  class tcp_server { public:     tcp_server(boost::asio::io_service& io_service,int port_number)         : acceptor_(io_service, boost::asio::ip::tcp::tcp::endpoint(boost::asio::ip::tcp::tcp::v4(), port_number))     {         std::cout << "TCP server listening on " << port_number << std::endl;         start_accept();     }  private:     void start_accept()     {         tcp_connection::pointer new_connection =             tcp_connection::create(acceptor_.get_io_service());          acceptor_.async_accept(new_connection->socket(),                                boost::bind(&tcp_server::handle_accept, this, new_connection,                                            boost::asio::placeholders::error));     }      void handle_accept(tcp_connection::pointer new_connection,                        const boost::system::error_code& error)     {         if (!error)         {             new_connection->start();             start_accept();         }     }      boost::asio::ip::tcp::tcp::acceptor acceptor_; };   void runTCPServer ( CmdLineOpts input ) {     try     {         boost::asio::io_service io_service;         tcp_server server(io_service,input.port);         io_service.run();     }     catch (std::exception& e)     {         std::cerr << e.what() << std::endl;     } }  class tcp_client { public:     tcp_client(         boost::asio::io_service& io_service,         const std::string& host,         const std::string& port     ) : io_service_(io_service), socket_(io_service, boost::asio::ip::tcp::tcp::endpoint(boost::asio::ip::tcp::tcp::v4(), 0))     {         boost::asio::ip::tcp::tcp::resolver resolver(io_service_);         boost::asio::ip::tcp::tcp::resolver::query query(boost::asio::ip::tcp::tcp::v4(), host, port);         boost::asio::ip::tcp::tcp::resolver::iterator iter = resolver.resolve(query);         endpoint_ = *iter;         boost::asio::connect(socket_, iter);     }      ~tcp_client()     {         socket_.close();     }       void recieve_from() {         /*Initialize our endpoint*/         size_t len = socket_.read_some(                          boost::asio::buffer(recv_buf), error);          if (error == boost::asio::error::eof)             std::cout << "Connction close cleanly by peer" << std::cout;         else if (error)             throw boost::system::system_error(error); // Some other error.          std::cout.write(recv_buf.data(), len) << std::endl;      }  private:     boost::asio::io_service& io_service_;     boost::asio::ip::tcp::tcp::socket socket_;     boost::asio::ip::tcp::tcp::endpoint endpoint_;     boost::array<char, 2048> recv_buf;     boost::asio::ip::tcp::endpoint sender_endpoint;     boost::system::error_code error;  };  void runTCPClient(std::string portStr) {     try     {         boost::asio::io_service io_service;         tcp_client client(io_service, "localhost", portStr);         client.recieve_from();     }     catch (std::exception& e)     {         std::cerr << e.what() << std::endl;     }  }  void runClient( CmdLineOpts input ) {     runTCPClient(input.portStr);  }  void runServer( CmdLineOpts input ) {     runTCPServer(input); }  /**  * * Usage: client_server <protocol> <port> <num of packets>  * */ bool cmdline_parse ( int argc, char *argv[], CmdLineOpts *input ) {     bool result = true;     if (argc - 1 == ARG_COUNT)     {         // arg 1: server or client         int arg1 = std::stoi(argv[1]);         if (arg1 == 0 || arg1 == 1)         {             input->servOrClient = arg1;         }         else         {             std::cout << "Invalid client server choice.\nUsage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;             result = false;         }         // arg 3: port         int arg2 = std::stoi(argv[2]);         if (arg2 > LOWEST_PORT && arg2 < HIGHEST_PORT )         {             input->port = arg2;             input->portStr = argv[2];         }         else         {             std::cout << "Invalid port, must be between " << LOWEST_PORT << " and " << HIGHEST_PORT << std::endl;             std::cout << "Usage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;             result = false;         }      }     else     {         std::cout << "Usage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;         result = false;     }      return result; }    int main ( int argc, char *argv[] ) {     CmdLineOpts input;     if (cmdline_parse(argc, argv, &input))     {         if(input.servOrClient == 1)         {             runServer(input);         }         else if(input.servOrClient == 0)         {             runClient(input);         }     }     else     {         return 1;     }      return 0; } 

test.hpp

#ifndef CLIENT_SERVER_H_INCLUDED                                                                                                                                                                                    #define CLIENT_SERVER_H_INCLUDED  #include <string>  struct CmdLineOpts {     std::string portStr;     int port;     int servOrClient; };  void runTCPServer ( CmdLineOpts input );  void runTCPClient ( std::string port_str);  bool cmdline_parse ( int argc, char *argv[], CmdLineOpts input ); #endif 

Makefile

TARGET = client_server                                                                                                                                                                                              LIBS = -lboost_system -lpthread CXX = g++  CXXFLAGS = -std=c++11 -g -Wall -pedantic  .PHONY: default all clean  default: $(TARGET) all: default  OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp)) HEADERS = $(wildcard *.hpp)  %.o: %.cpp $(HEADERS)   $(CXX) $(CXXFLAGS) -c $< -o [email protected]  .PRECIOUS: $(TARGET) $(OBJECTS)  $(TARGET): $(OBJECTS)   $(CXX) $(OBJECTS) $(LIBS) -o [email protected]  clean:       -rm -f *.o       -rm -f $(TARGET) 
Tags:c++11, boost

Related Articles

  • boost::shared_ptr does not have a class typeMarch 13

    I have implemented a tcp client and tcp server using boost asio. The code is given below. (test.cpp, test.hpp and makefile) The executable can be run as (server side) $ ./client_server 1 5005 (client side) $ ./client_server 0 5005 tcp_sever uses a ho

  • Boost.Python boost::shared_ptr no to python by value converter foundJanuary 19

    I have the given code, In A.hpp typedef boost::shared_ptr<A> APtr; and In B.hpp typedef std::vector<APtr> APtrCollection; typedef boost::shared_ptr<APtrCollection> APtrCollectionPtr; APtrCollectionPtr a_ptr; APtrCollectionPtr B::get_item

  • Boost shared_ptr example programFebruary 11

    I was trying to get familiar with boost shared ptr. I came across the following example. #include <vector> #include <set> #include <iostream> #include <algorithm> #include <boost/shared_ptr.hpp> /* The application will produc

  • How to print a vector of boost::any, when i have the element types stored in another vector of strings? February 6

    This question already has an answer here: How to print boost::any to a stream? 6 answers I'm using a vector of boost::any to store different data types, to construct a symbol table from a given program file. I'm also storing their datatypes in a sepa

  • boost::enable_if_c error: is not a valid type for a template non-type parameterJanuary 19

    I want to disallow instantiating a class template (PointCloud) for types with particular type traits. In the following example, I want to only allow types with is_good defined to be used: #include <boost/core/enable_if.hpp> class PointType1 {}; clas

  • Opaque Type C-pointer to shared_ptrJanuary 21

    I came across the following situation.(Update: Known as Opaque Type; Thanks for info @iharob) Type P is typedef-ed in public_api.h along with some functions that create, modify and destroy it, eg. createP in following snippet. However, its implementa

  • How to use Boost in Visual Studio 2010

    How to use Boost in Visual Studio 2010April 13

    What is a good step by step explanation on how to use Boost in an empty project in Visual Studio 2010. --------------Solutions------------- While Nate's answer is pretty good already, I'm going to expand on it more specifically for Visual Studio 2010

  • shared_ptr implementationSeptember 2

    I've written a linked-list version of something like shared_ptr, which gets destroyed when the last copy of a pointer is destroyed. Aside from the thread-unsafety, is it a fine implementation? Anything I could improve? Also, what's the best way to ex

  • Where to start learning to use the Boost libraries?October 4

    Boost has recently become available on the project on which I'm working, and I don't have much experience with it. The library has so many parts and features that it's hard to know where to get started in learning it - especially since I'll be trying

  • What are the personal benefits from writing a boost libraryDecember 2

    Among the reasons for a developer to publish a self-written library as open source library, there is definitely fame. Now when it comes to Boost Libraries, they are available and promoted in a very anonymous and impersonalized form. The name of the a

  • std::shared_ptr as a last resort?February 4

    I was just watching the "Going Native 2012" streams and I noticed the discussion about std::shared_ptr. I was a bit surprised to hear Bjarne's somewhat negative view on std::shared_ptr and his comment that it should be used as a "last resor

  • Have I thought of everything in this wrapper around boost::thread_group?February 26

    boost::thread_group doesn't automatically clean up contained threads when they end, so I needed something like that described in this boost-users list post. However, in my opinion that code is not safe, because there's no guarantee that tp will be .r

  • How to convert boost::exception_ptr to my customized exception class pointer and vice-versaJanuary 27

    I am using boost 1.58.0 and GCC 4.8 to compile the code. Below is my custom Exception class, all my exceptions should derive from this. class MyException : public virtual std::exception, public virtual boost::exception { public: explicit MyException(

  • Boost.regex with icu support using named capture groupsFebruary 8

    Below test program uses the named captures support in boost-regex to extract year, month and day fields from a date (just to illustrate the use of named captures): #include <boost/regex.hpp> #include <boost/regex/icu.hpp> #include <string&g

  • Build process crashes with boost and C++11February 10

    What I have: I am writing Qt application for Linux (I work in Linx Mint 17.3 64-bit) I use C++11 features in my Qt project (Qt ver 5.5) I want to add libslave to my Qt project. libslave uses deprecated (for C++11) boost::function, boost::shared_ptr,

  • Singleton Boost-based timerSeptember 5

    I would like a review on this code, and how I could make it better. #include <boost/bind/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/function.hpp> #include <boost/thread/thread.hpp> #include <b

  • Installing boost asio on CentOS 5April 21

    I tried running: yum install boost boost-devel boost-doc (1/3): boost-1.33.1-15.el5.i386.rpm (2/3): boost-doc-1.33.1-15.el5.i386.rpm (3/3): boost-devel-1.33.1-15.el5.i386.rpm Then it successfully installed the boost lib, but when I compile my script:

  • Trying to find a good design for reading in values of different types from a fileAugust 7

    I have implemented the following code which will be used to read in what are essentially key-value pairs from a file. an example input file may look like max_search_depth 10 enable_recursion false job_name Khalessi my main issue with this code is tha

  • Is it not direct usage of primitive pointer types form of Primitive Obsession?February 8

    Using primitive data types to represent domain ideas is code smell called Primitive Obsession. For example using string data type to represent human name - it is recomended to avoid this by defining domain specific value object with apropriate method

  • Template based return type from object and class methodFebruary 18

    I'm looking for a better implementation of this. The current solution looks bad to me and breaks the VC10 compiler if you call Create() with a method expecting two parameters. Can this be reworked to be more compatible across compilers (at least VC10

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.606 s.