G
gao_bolin
I am facing the following scenario: I have a class 'A', that implements
some concept C -- but we know this, not because A inherits from a
virtual class 'C', but only because a trait tell us so:
class A {};
template <typename T>
struct Is_C
{
static const bool value = false;
};
template <>
struct Is_C<A>
{
static const bool value = true;
};
What I would like to do is, given an instance 'a' of A, call a function
'foo(a)' that would have specific code for class A -- and have default
code for other classes.
The following
template < typename T >
void foo(T t)
{
if (Is_C<T>::value)
{
/* ... */
}
else
{
/* ... */
}
}
would work, but then, it is not extensible to another trait 'Is_D'
unless I modify the function foo. Ideally I would have a function foo
for the general case (corresponding to the 'else') and as many
functions foo for all the different tests, but I am not sure how to do
that. I would like to use the boost::enable_if, but if I use function
overloading, I need to have a disable_if in my 'general case' foo for
each 'specialized' foo:
// General case
template < typename T >
typename disable_if<Is_C<T> >::type // This has to be modified if
another foo is added
foo(T t)
{
/* ... */
}
// Specialization for concept C
template < typename T >
typename enable_if<Is_C<T> >::type
foo(T t)
{
/* ... */
}
I would really appreciate any suggestion for this problem.
Thanks
B.
some concept C -- but we know this, not because A inherits from a
virtual class 'C', but only because a trait tell us so:
class A {};
template <typename T>
struct Is_C
{
static const bool value = false;
};
template <>
struct Is_C<A>
{
static const bool value = true;
};
What I would like to do is, given an instance 'a' of A, call a function
'foo(a)' that would have specific code for class A -- and have default
code for other classes.
The following
template < typename T >
void foo(T t)
{
if (Is_C<T>::value)
{
/* ... */
}
else
{
/* ... */
}
}
would work, but then, it is not extensible to another trait 'Is_D'
unless I modify the function foo. Ideally I would have a function foo
for the general case (corresponding to the 'else') and as many
functions foo for all the different tests, but I am not sure how to do
that. I would like to use the boost::enable_if, but if I use function
overloading, I need to have a disable_if in my 'general case' foo for
each 'specialized' foo:
// General case
template < typename T >
typename disable_if<Is_C<T> >::type // This has to be modified if
another foo is added
foo(T t)
{
/* ... */
}
// Specialization for concept C
template < typename T >
typename enable_if<Is_C<T> >::type
foo(T t)
{
/* ... */
}
I would really appreciate any suggestion for this problem.
Thanks
B.