【发布时间】:2013-04-04 12:43:54
【问题描述】:
我对以下问题感到困惑。我想写一些特征结构来测试某个类是否是从另一个类派生的。这可以通过 boost::is_base_of 解决。但是,我要测试的基类有一个免费的未定义模板参数。
下面是一些代码示例:
template<typename T> class Base {};
class IntDeriv : Base<int> {};
class Foo {};
template< class TestClass >
struct is_derived_from_Base {
// how to create something that does the following and forces the compiler to deduce T
static const bool value = boost::is_base_of< Base<T> , TestClass >::value;
};
int main() {
cout << is_derived_from_Base<Foo> << endl; // should print 0
cout << is_derived_from_Base<IntDeriv> << endl; // should print 1
}
问题是如何在is_base_of 中推导出Base<T> 的T。
这可能吗?我闻到了一些 enable_if 的味道,但我不知道如何组合起来。
【问题讨论】:
-
是的,这也是我的第一个猜测。但是,有几个类似的问题可以通过一些 enable_if/SFINAE 魔法来解决。关键是编译器实际上不需要推导出 T。我只想知道某个类是否从 Base 派生为某个任意 T。
-
@jrok 这是可能的,看我的回答。请注意,该方法可以扩展以查找基的类型。
标签: c++ templates metaprogramming