我有以下情况。
template <class T>
class Foo {
template <class V>
int bar();
};
(我正在使用 swig 将此类移植到 python,澄清一下)
我遇到的问题是因为实际的模板参数 T 和 V 是相关的,即 Foo<T1>
应该有 bar<V1>
, Foo<T2>
应该有 bar<V2>
等等。但是,我所处的情况是 swig(或 C++ 编译器)假装定义了所有可能的组合,即 Foo<T1>::bar<V1>
, Foo<T1>::bar<V2>
, Foo<T2>::bar<V1>
等等。这意味着我必须提供 Tn * Vn 方法,除了对角线组合 Ti/Vi 之外,大多数方法都会引发异常
有没有一种聪明的方法来防止这种情况发生,还是我应该咬紧牙关实现所有组合?如果您认为我有设计问题,您会如何解决?
最佳答案
如果 T
和 V
之间存在 1-1 映射,为什么 bar
需要是模板?您可以创建特征类来确定正确的 V
,如下所示:
template <typename T>
struct Match_T_V;
template <>
struct Match_T_V<T1> {
typedef V1 type;
};
template <>
struct Match_T_V<T2> {
typedef V2 type;
};
//etc. for other Ts
template <typename T>
class Foo {
typedef typename Match_T_V<T>::type V;
int bar(); //use V, guaranteed to be the correct one
};
关于c++ - 类和方法上的模板是相关的。如何防止组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16314763/