我是metafunctions的新手 . 我想编写一个函数,用一些其他类型替换复合类型中某种类型的所有匹配项 . 例如: replace<void *, void, int>::type
应为 int *
, replace<void, void, int>::type
应为 int
等 .
到目前为止我基本上失败了两种不同的方法:
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;
};
这对我来说似乎很简单,但我发现当我尝试 replace<void *, void *, int>
时,编译器无法决定是否在这种情况下使用 replace<C, C, Y>
或 replace<C *, X, Y>
,因此编译失败 .
我试过的下一件事就是在基函数中剥离指针:
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;
};
......这时我发现我也不能这样做,因为 type
显然没有在那时定义,所以我不能从基函数做递归 typedef
.
现在我没有想法 . 你怎么解决这个问题?
3 回答
你试过的东西:
Kerrek的答案看起来好多了:)
这是一个大致的想法:
测试:
打印:
Edit: 这是一个更完整的集合:
按照您的代码,为什么不再添加一个专业化
实时代码example results
或者更多:
实时代码results