这可能非常愚蠢......
如果我有这样一个模板类A,
template <class T1, class T2>
struct A
{
T1 a;
T2 b;
};
一个函数作用于它,
template <class T1, class T2>
void foo(A<T1, T2> *p)
{
}
现在我子类化A,
struct B : A<int, int>
{
};
B b[100];
我无法推断模板参数...
foo(b);
我必须这样写,
foo((B *)b);
或者像这样,
foo<int, int>(b);
现在还有更多, 我希望 foo 可以接受 A 以外的 T 并将它们视为 A
template <class T>
struct A<T, void>
{
T a;
};
template <class T>
void foo(T *p)
{
foo((A<T, void> *)p);
}
现在除非我这样写,后面的foo就叫...
foo<int, int>(b);
- 我怎样才能更容易地从子类数组中推导出模板参数?
- 如何让子类在定位重载函数时比其他类有更高的优先级?
这似乎可以了
template <class T>
struct is_A_derived
{
typedef char (&yes)[1];
typedef char (&no)[2];
template <class T1, class T2>
static yes test(A<T1, T2> *);
static no test(...);
template <class T1, class T2>
static A<T1, T2> get_type(A<T1, T2> *);
static A<T, void> get_type(...);
template <class T1, class T2>
static A<T1, T2> base_type(A<T1, T2> *);
static int base_type(...); // guess or maybe hope this "int" is never used
static const bool value = sizeof(test((T *)0)) == sizeof(yes);
static const bool identical = value && sizeof(base_type((T *)0)) == sizeof(T);
typedef typename std::conditional<identical, decltype(get_type((T *)0)), A<T, void>>::type type;
};
最佳答案
请注意,此代码将失败。您不能以多态方式使用 C 样式数组(无论模板如何)。
也就是说,您不能将B
数组视为A
数组。
如果你写p[1]
,你认为会发生什么?那么,内部会发生以下情况:
*(p + 1)
指针运算。现在,编译器将 + 1
进一步翻译为 sizeof A
字节的增量。但是你的数据结构不是 sizeof A
大,而是 sizeof B
!所以 p[1]
会指向错误的内存位置。
因此编译器(完全是意外!)通过禁止此调用来做正确的事情。
关于c++ - 如何使用模板类的子类推导C++中模板函数的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9513722/