在我的一个项目中,我有以下类模板层次结构:
template <typename FruitType, typename ParentFilterType = void>
class filter;
template <typename FruitType> // Specialization when no parent filter is needed
class filter<FruitType, void>;
其中 FruitType
可以是任何内容。假设它是 apple
、banana
或 orange
之一。
所以基本上,filter
可以有自己的父 filter
类型。
我无法控制过滤
代码:它必须保持原样。
用户代码通常如下所示:
filter<apple, filter<banana, filter<orange> > > my_apple_filter;
显然,这有点冗长。我想知道是否有可能获得更具可读性的东西。类似于:
complex_filter<apple, banana, orange>::type my_apple_filter;
其中 complex_filter::type
将解析为 filter > >
。
我尝试将complex_filter
作为一个struct
模板,其中包含typedef
,但到目前为止没有成功。模板参数的数量应该是可变的(例如,从 1 到 5)。
您是否曾经需要过类似的东西?我怎么能这么做呢?
(不幸的是,我无法使用 C++0x,但如果有更好的解决方案,请随时发布它,因为知道它总是很高兴)
谢谢。
In one of my projects, I have the following class template hierarchy :
template <typename FruitType, typename ParentFilterType = void>
class filter;
template <typename FruitType> // Specialization when no parent filter is needed
class filter<FruitType, void>;
Where FruitType
can be anything. Let's say it is one of apple
, banana
or orange
.
So basically, a filter
can have its own parent filter
type.
I have no control over the filter
code: it must remain as it is.
The user code usually looks like:
filter<apple, filter<banana, filter<orange> > > my_apple_filter;
Obviously, this is a bit verbose. I wondered if it is possible to get something more readable. Something like:
complex_filter<apple, banana, orange>::type my_apple_filter;
Where complex_filter<apple, banana, orange>::type
would resolve to filter<apple, filter<banana, filter<orange> > >
.
I tried with complex_filter
being a struct
template with a typedef
inside but had no success so far. The number of template parameters should be variable (from, say, 1 to 5).
Have you ever needed something similar ? How could I do that ?
(I unfortunately cannot use C++0x but if there is a nicer solution with it, feel free to post it as it is always good to know)
Thank you.
发布评论
评论(2)
在 C++0x 中,它将是可变参数模板。
如果没有 C++0x,您可以简单地使用大量参数,并提供默认值。
然后可以根据需要使用它,如果您需要更多参数,则必须手动扩展它。
In C++0x, it would be variadic template.
Without C++0x, you can simply use a large list of parameters, with defaults supplied.
This can then be used as you wanted, and you will have to extend it manually if you ever want more parameters.
你尝试过的应该有效,有点:
what you tried should work, sort of: