I am new to metafunctions. I want to write a function that replaces all matches of a certain type in a compound type with some other type. In example: replace<void *, void, int>::type should be int *, replace<void, void, int>::type should be int, etc.
I basically failed with two different approaches so far:
template
<
typename C, // Type to be searched
typename X, // "Needle" that is searched for
typename Y // Replacing type
>
struct replace
{
typedef C type;
};
// If the type matches the search exactly, replace
template
<
typename C,
typename Y
>
struct replace<C, C, Y>
{
typedef Y type;
};
// If the type is a pointer, strip it and call recursively
template
<
typename C,
typename X,
typename Y
>
struct replace<C *, X, Y>
{
typedef typename replace<C, X, Y>::type * type;
};
This seemed pretty straight forward to me, but I discovered that when I try replace<void *, void *, int>, the compiler cannot decide whether to use replace<C, C, Y> or replace<C *, X, Y> in that case, so compilation fails.
The next thing I tried is to strip pointers in the base function already:
template
<
typename C,
typename X,
typename Y
>
struct replace
{
typedef typename boost::conditional
<
boost::is_pointer<C>::value,
typename replace
<
typename boost::remove_pointer<C>::type,
X, Y
>::type *,
C
>::type
type;
};
…and this is when I found out that I cannot do that either, because type is apparently not defined at that point, so I cannot do recursive typedef from the base function.
Now I am out of ideas. How would you solve such a problem?
Here’s a general idea:
Test:
Prints:
Edit: Here’s a somewhat more complete set: