【发布时间】:2014-03-24 22:38:14
【问题描述】:
我想让一个特征类应用于一个类型以及它的后代。这可能吗?
template <typename E>
struct Garble {
};
template <typename T>
struct wooble_traits;
template <typename E>
struct wooble_traits<Garble<E>> {
typedef E elem_type;
};
struct IntGarble : public Garble<int> {
};
typedef typename wooble_traits<IntGarble>::elem_type IGType;
//Error, wooble_traits<IntGarble> has no definition.
有什么办法可以代替说(借用和滥用 Java 表示法):
template <typename E>
struct wooble_traits<? extends Garble<E>> {
typedef E elem_type
};
typedef typename wooble_traits<IntGarble>::elem_type IGType;
//Fine, IGType is an alias for int
注意:
尝试使 Dyp 的解决方案适应我的示例不起作用,因为 Garble 采用类型参数。似乎没有任何地方可以推断该参数。
#include <boost/type_traits/is_base_of.hpp>
template <typename T, typename C = void>
struct wooble_traits;
template <typename T, typename E>
struct wooble_traits<T, typename boost::is_base_of<Garble<E>, T>::type> {
typedef E elem_type;
};
在 gcc-4.6 中,这会产生:
g++ -I/usr/include/boost/utility -I/usr/include/boost/type_traits -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp:15:8: error: template parameters not used in partial specialization:
../main.cpp:15:8: error: ‘E’
make: *** [main.o] Error 1
这是可以理解的,因为 GCC 无法知道 E 的值。
【问题讨论】:
-
@Jefffrey:例如
IntGarble。子类/派生类。 -
我的后代是指派生类。特征类使有关类型的信息在编译时可用。 wooble_traits 公开 wooble 的 elem_type 以在编译时使用。当被视为 wooble 时,Garble 的 elem_type 与其模板参数相同。来自某些 Garble(包括 IntGarble)的所有派生类都具有与其 Garble 祖先相同的 elem_type(在 IntGarble 的情况下,此类型为 int)。
标签: c++ templates inheritance template-specialization typetraits