I'd love to be able to use references to another namespace within a class without committing the error/sin of introducing that namespace into my caller's compilation units.
The only way I am aware of to do that now is to move everything into my .cpp file, where I can declare a using namespace XYZ
without worries.
But what if I'm defining a template? Or I just want to put this code in my header?
For example, I want to use namespace Toolbox from which Toolbox::FormatString
lives, and there are many other useful tools there - but I cannot? I have to specify every reference as Toolbox::FormatString
?
class CHaspException : public CLabeledException
{
public:
CHaspException(haspStatus status) :
CLabeledException(FormatString(_T("HASP Error %u: %s"), (unsigned)status, GetHaspErrorMessage(status))),
m_status(status)
{
}
CHaspException(const char * source, haspStatus status) :
CLabeledException(FormatString(_T("%hs: HASP Error %u: %s"), source, (unsigned)status, GetHaspErrorMessage(status))),
m_status(status)
{
}
CHaspException(const char * source, const char * api, haspStatus status) :
CLabeledException(FormatString(_T("%hs: %hs() returned %u: %s"), source, api, (unsigned)status, GetHaspErrorMessage(status))),
m_status(status)
{
}
CHaspException(const char * source, const char * api, const CString & args, haspStatus status) :
CLabeledException(FormatString(_T("%hs: %hs(%s) returned %u: %s"), source, api, args, (unsigned)status, GetHaspErrorMessage(status))),
m_status(status)
{
}
haspStatus GetStatus() const { return m_status; }
private:
haspStatus m_status;
};
This is a simple example, but I can imagine others where there are more diverse references. In fact code which uses the global begin()
and end()
is supposed to bring the std namespace into scope, but not actually specify it literally - i.e. it should do:
template <typename T> myfun(T & x)
{
using namespace std;
if (begin(x) == end(x))...
}
So that std is available for resolving begin/end, but it is not forced (not use std::being(x)
).
So, again, it seems crucial that classes be able to pull a namespace into scope, no?
What's the deal, or what is the right way to do this?
Not a duplicate of that question - though that's an excellent and interesting discussion. Here, I'm flummoxed by the need to tell the compiler "allow resolution in this given scope, but allow type-specific lookup to override that" while restricting the scoping of that directive to just my class or header.
In my second example - which is the "best practices" approach as given by the standards body, I cannot do that. I have no valid scope to work with at a header or class declaration level...