I'm C++ newbie here. I'm trying to implement something. My goal is simple:
- A shared instance which can be easily accessed in different scopes.
- This shared instance has a dictionary instance variable (map) to store key-value pair data.
- We can add a new key-value pair or get the value for a key via the public accessor.
Here is my header:
// .h
using namespace std;
class Person;
typedef map<string, Person> DictForPeople;
class Company {
Company();
void setValueForKey(string key, Person value);
Person valueForKey(string key);
private:
DictForPeople _dictForPeople;
};
class Person {
public:
Person();
void setName(string name);
string name();
private:
string _name; // !!!: raise error here
};
and the implementation (.cpp):
// .cpp
Company::Company(){
}
void Company::setValueForKey(string key, Person value){
_dictForPeople[key] = value;
}
Person Company::valueForKey(string key){
return _dictForPeople[key];
}
Person::Person(){
}
void Person::setName(string name){
_name = name;
}
string Person::name(){
return _name;
}
I'm trying to use singleton pattern, but it raises a lot of compilation errors. How to correctly declare a shared instance with accessors for string/map?
UPDATE 1:
The above code raises an error: Implicit instantiation of undefined template 'std::__1::basic_string, std::__1::allocator >'
The environment is Xcode 6/Mac OS X 10.10 with LLVM/Clang. I'm trying using C++ instead of Objective-C for some reasons.
UPDATE 2:
My implementation with Singleton Pattern is the following (reference):
// .h
using namespace std;
class Person;
typedef map<string, Person> DictForPeople;
class Company {
static Company& getInstance() { // For Singleton Pattern
static Company instance;
return instance;
}
void setValueForKey(string key, Person value);
Person valueForKey(string key);
private:
Company() {}; // For Singleton Pattern
Company(Company const&); // For Singleton Pattern
void operator=(Company const&); // For Singleton Pattern
DictForPeople _dictForPeople;
};
class Person {
public:
Person();
void setName(string name);
string name();
private:
string _name; // !!!: raise error here
};
This change raises more errors:
- Field has incomplete type 'Person': this could be fixed by moving the class declaration
Person
above the class declarationCompany
. Other errors are the same message introduced before (Implicit instantiation of undefined template 'std::__1::basic_string, std::__1::allocator >') but in different places. The C++ file
utility
LLVMtemplate <class _T1, class _T2> struct _LIBCPP_TYPE_VIS_ONLY pair { typedef _T1 first_type; typedef _T2 second_type; _T1 first; // <<<-- raise the error here _T2 second; // pair(const pair&) = default; // pair(pair&&) = default; _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR pair() : first(), second() {}
Update 3:
I forgot to mention that the above code is embedded in extern "C" {...}
block.