【发布时间】:2016-10-21 18:53:58
【问题描述】:
我在基类中有一个方法,它需要将类型传递给它以进行一些与类型相关的操作(查找、大小和一些方法调用)。目前它看起来像这样:
class base
{
template<typename T>
void BindType( T * t ); // do something with the type
};
class derived : public base
{
void foo() { do_some_work BindType( this ); }
};
class derivedOther : public base
{
void bar() { do_different_work... BindType( this ); }
};
但是,我想知道是否有一种方法可以获取调用者的类型而无需传递它,以便我的调用点代码变为:
class derived : public base
{
void foo() { BindType(); }
};
没有明确的 this 指针。我知道我可以将模板参数显式提供为BindType<derived>(),但是有没有办法以某种其他方式提取调用者的类型?
【问题讨论】:
-
这是一个典型的 CRTP 用例stackoverflow.com/questions/4173254/…
-
在基类中使用
typeid(*this)? -
@davmac typeid 并没有以我可以使用的方式给我类型,比如调用 sizeof(T) 或 T::SomeFunction() - 它只给我 typeid。
-
@Steven 对,但你的问题只是说你需要它来“一些类型到索引的查找代码”,为此它应该没问题。
-
@davmac 很公平 - 我会更新问题。
标签: c++ templates types type-deduction