Hi. I'm new. I try to create abstract database class Db and derived class Pg to handle at least connection to the database. I have private property with database connection type and because it will be unique depending on database I should implement templates.
Code:#include <iostream> #include <postgresql/libpq-fe.h> using namespace std; template <class T> class Db { public: Db(string, string, string, string); Db(); string getHost(); string getUsername(); string getDatabase(); string getPassword(); virtual string getConnectionString()=0; virtual ~Db(); protected: T* m_conn; string m_host; string m_username; string m_database; string m_password; }; template <class T> class Pg : public Db<T> { public: Pg(string, string, string, string); Pg(); virtual ~Pg(); virtual string getConnectionString(); }; template <class T> string Db<T>::getHost() { return m_host; } // --------------------------------------------------------------------- // username, database and password getters are implementing the same way // --------------------------------------------------------------------- template <class T> Pg<T>::Pg(string host, string username, string database, string password) // I intentionally remove Pg:: for m_host property : m_host(host), Pg::m_username(username), Pg::m_database(database), Pg::m_password(password) { Pg::m_conn = PQconnectdb(getConnectionString().c_str()); if (PQstatus(Pg::m_conn) == CONNECTION_BAD) { puts("Unable to connect to database"); exit(0); } } template <class T> string Pg<T>::getConnectionString() { return "host=" + this->getHost() + " user=" + this->getUsername() + " password=" + this->getPassword() + " dbname=" + this->getDatabase(); } int main () { Pg<PGconn> conn("localhost", "pg", "pg", "pwd"); return 0; }
When I compile this beautiful code I get an errors:
As you can see if I remove Pg:: before m_host property I get the error that class does not have such field. If I place Pg:: before another connection properties I get the error no type named ‘m_database’.Code:load.cpp: In constructor ‘Pg<T>::Pg(std::string, std::string, std::string, std::string)’: load.cpp:50:7: error: class ‘Pg<T>’ does not have any field named ‘m_host’ : m_host(host), Pg::m_username(username), Pg::m_database(database), Pg::m_password(password) { ^ load.cpp: In instantiation of ‘Pg<T>::Pg(std::string, std::string, std::string, std::string) [with T = pg_conn; std::string = std::basic_string<char>]’: load.cpp:73:52: required from here load.cpp:50:96: error: no type named ‘m_username’ in ‘class Pg<pg_conn>’ : m_host(host), Pg::m_username(username), Pg::m_database(database), Pg::m_password(password) { ^ load.cpp:50:96: error: no type named ‘m_database’ in ‘class Pg<pg_conn>’ load.cpp:50:96: error: no type named ‘m_password’ in ‘class Pg<pg_conn>’
I completely stuck for two days with this issue.
I use linux and g++ compiler:
g++ -o load -g load.cpp -std=c++11 -lcurl -lpq




Reply With Quote
