使用类似模板的机制调用具有相同签名的不同方法
Calling different methods with the same signature using a template like mechanism
我有这个代码:
struct C
{
int d1;
int d2;
};
struct A
{
void write(C data)
{
}
};
struct B
{
void use(C data)
{
}
};
现在,我想定义一个使用 A
或 B
的新类,并调用它们的 write
和 use
方法。像这样的东西:
template <class T>
struct D
{
T t;
D(T myT) { t=myT; }
void myFunct(C data)
{
// t.????(data);
}
};
如您所见,如果这两个类具有相似的方法名称,那么D
实现就很容易了,但是由于A
和B
有不同的方法,那么我需要告诉编译器它应该使用哪个方法。我该怎么做?
我不想更改A
或B
,也不想创建A
的子类,B
创建具有相同名称的方法。
我想要一种方法来告诉编译器将哪种方法用作模板的一部分,可以吗?
您可以将指向成员函数的指针作为第二个模板参数传递给D
:
template <class T, void (T::*fun)(C)>
struct D
{
T t;
void myFunct(C data)
{
(t.*fun)(data);
}
};
然后,您可以通过以下方式创建D
对象:
D<A, &A::write> da;
D<B, &B::use> db;
您可以使用自己的 trait 类轻松执行此操作:
template <class T>
struct DTraits;
template <>
struct DTraits<A> {
static void call(A &obj, C data) { obj.write(data); }
};
template <>
struct DTraits<B> {
static void call(B &obj, C data) { obj.use(data); }
};
template <class T>
struct D
{
void myFunct(C data)
{
DTraits<T>::call(t, data);
}
};
为了完整起见,这里是另一种可能的解决方案,它使用 if constexpr
、 类型特征并需要 C++17 支持:
void myFunct(C data)
{
if constexpr (std::is_same_v<T, A>) {
t.write(data);
} else {
t.use(data);
}
}
例
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用