|
Boost Users : |
From: François Duranleau (duranlef_at_[hidden])
Date: 2006-05-10 22:58:01
On Wed, 10 May 2006, Rush Manbert wrote:
> I have a template class that is designed to contain built in types or
> std::string types. I always need to be able to cast an instance of the
> class as a std::string, and I also need to be able to cast it as the
> parameter type with which it was instantiated.
>
> In my class definition, I have defined two cast operators, like so:
> (Extraneous stuff omitted)
[...]
> I thought that if I could conditionally define the cast as T operator
> (or the cast as std::string) I would be okay, but that means testing
> against the value of T with the preprocessor. I don't see how to do
> that, but I know that some of you folks are really good at bending the
> preprocessor to your will.
>
> Can anyone show me a way out of this predicament?
No need for the preprocessor. It can all be done with templates. I could
imagine something like this:
template < typename Derived ,
typename T >
struct convert_operator
{
operator const T& ()
{
// ... your code, you can access the subclass with:
// static_cast< Derived& >( * this )
// Add a const before Derived if the operator is const
}
} ;
template < typename Derived >
struct convert_operator< Derived , ::std::string >
{
// nothing
} ;
template < typename T >
class MyDataObject
: public MyDataObjectBase
, public convert_operator< MyDadaObject< T > , T >
{
// Cast as std::string
operator const std::string& ()
{
// ...some code here
}
// ...
} ;
-- François Duranleau LIGUM, Université de Montréal "As the caterpillar chooses the fairest leaves to lay her eggs on, so the priest lays his curse on the fairest joys." - William Blake, _Marriage of Heaven & Hell_
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net