【发布时间】:2012-05-16 08:04:12
【问题描述】:
我是元函数的新手。我想编写一个函数,将复合类型中某种类型的所有匹配项替换为其他类型。例如: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。
现在我没有想法了。你会如何解决这样的问题?
【问题讨论】:
-
让我看看我是否理解目标,给定两种模式,从差异中提取 const-volatile 和指针的差异并将其应用于第三个参数的类型?我不太确定问题是否明确,例如
replace<const void, void, const int>::type的输出是什么?replace<void,int,double>呢? -
@David Rodríguez - dribeas:问题出自《C++ 模板元编程:Boost 及其他领域的概念、工具和技术》一书中的练习。也许我没有正确表达。练习内容为:
Write a ternary metafunction replace_type<c,x,y> that takes an arbitrary compound type c as its first parameter, and replaces all occurences of a type x within c with y. -
我必须承认,书中的描述 together 和示例胜过原始问题
标签: c++ boost metaprogramming template-meta-programming boost-mpl