我正在用 C++ 编写一些模板代码,如果我能确定 this
的类型,它会使代码更短/更好/更可用。我不想使用 C++0x,因为代码要与旧编译器向后兼容。我也不想使用 BOOST。我所拥有的是这样的:
struct MyLoop {
template <class Param>
void Run(int iterations, Context c)
{
MyUtility<MyLoop>::template WrapLoop<Param>(iterations, c);
}
};
这可以用于一些有趣的循环优化。我不喜欢在
MyLoop
模板特化中使用 MyUtility
。使用 C++0x,可以使用类似的东西:struct MyLoop {
template <class Param>
void Run(int iterations, Context c)
{
MyUtility<decltype(*this)>::template WrapLoop<Param>(iterations, c);
}
};
这具有不重复类名的优点,整个事情可以隐藏在一个宏中(例如一个名为
DECLARE_LOOP_INTERFACE
的宏)。在没有 BOOST 的情况下,有没有办法在 C++03 或更早版本中做到这一点?我将在 Windows/Linux/Mac 上使用该代码。我知道语法很难看,它是一个研究代码。请不要介意。
最佳答案
我相信这应该有效:
template <class Param, class Loop>
void Dispatcher(Loop *loop_valueIsNotUsed, int iterations, Context c)
{
MyUtility<Loop>::template WrapLoop<Param>(iterations, c);
}
// Usage:
struct MyLoop
{
template <class Param>
void Run(int iterations, Context c)
{
Dispatcher<Param>(this, iterations, c);
}
};
Loop
将从调用中推导出来。