模板方法允许跨越一组不同静态类型参数的方法实例。自动参数推导避免信息重复。
我们面临这样一种情况,在这种情况下,我们希望自动推断为模板参数的静态类型是类实例本身的类型。 (在调用站点上,实例的类型可以是比声明模板方法的类更特殊的类型。)
例如。
class Base
{
public:
template <class T_callingObject>
T_callingObject foo()
{
bar += 1;
// We have a strong guarantee on this cast only if T_callingObject
// is automatically deduced !
return static_cast<T_callingObject&>(*this);
}
private:
int bar;
};
class Derived : public Base
{
};
int main()
{
Base base;
Derived derived;
base = base.foo<Base>(); // we already know the type of base is Base
derived = derived.foo<Derived>(); // idem
}
问题是:有没有办法不重复base
和derived
的类型?
编辑:Base
上的 CRTP 在这里不是一个选项,我们需要有一个共同的祖先类型。
最佳答案
这通常通过制作 Base
来使用 CRTP(好奇递归模板模式)来解决。模板本身:
template <typename D>
struct Base {
D& foo() { return static_cast<D&>(*this); }
};
因此 struct Derived: Base<Derived>
.
您可以在 D
上执行的一组操作参数受到限制(在实例化 Base<Derived>
时这是一个不完整的时间),但在您的简单情况下这是有效的。
你仍然想知道是否有人会无意中写下 struct Bar: Base<Foo>
不过,这只会减少有问题的表面。
编辑:如果 CRTP 为 Base
不允许(经常发生),你可以分层抽象:
struct Base { virtual ~Base() {} };
template <typename D>
struct BaseT: Base {
D& foo() { return static_cast<D&>(*this); }
};
struct Derived: BaseT<Derived> {};
因为一般 if foo
需要知道什么D
是,您不再有单一的统一类型。
关于c++ - 是否可以将调用站点上对象的静态类型用作其模板方法的自动推导模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24550517/