I'm writing a wrapper to use around the Boost library's locale::date_time class, to make it friendlier and easier for me to use. One thing I've figured out is that a date_time object cannot be declared (or be a member of a wrapper class that is declared) unless a locale generator has been created first.
So I need to ensure that a locale generator has been created BEFORE I create an instance of my wrapper object (which necessarily has a date_time member object). What is the best pattern/implementation to do this?
#include <boost\locale\date_time.hpp>
#include <boost\locale.hpp>
class DateTimeWrapper
{
public:
boost::locale::date_time m_date_time_object;
};
void Initialize_Locale()
{
// Create locale generator
boost::locale::generator gen;
std::locale::global(gen(""));
}
int main()
{
Initialize_Locale();
// The following declaration will cause a failure if the above function is not first called
DateTimeWrapper example_wrapper;
return(0);
}
The problem with the above code is that I can't just blindly plug in my DateTimeWrapper class into any source file I want, unless I'm confident that main() or another function has called Initialize_Locale() first. I don't want to always have to watch out for that loose end in future projects if I want to reuse my DateTimeWrapper code - I'd rather just drop in the source file and have it work, without also having to ensure that main() or other function calls the Initialize_Locale() function.
I don't like that dependency - and making Initialize_Locale() a function of DateTimeWrapper that's called in the constructor also does not work, because the member m_date_time_object will still cause a failure when initialized before any DateTimeWrapper constructor code is run.
The only solution I can think of is to make m_date_time_object a pointer and dynamically allocate m_date_time_object in the constructor, AFTER the constructor calls Initialize_Locale(). But dynamically allocating m_date_time_object (and deleting it on destruction) will introduce a lot more complexity (related to how I'm implementing the DateTimeWrapper's other functionality), so I would like to avoid that solution if possible.
Is there an alternative pattern or approach I can use to address this problem?
Thanks.
Aucun commentaire:
Enregistrer un commentaire