假设我有一个带有单个非类型模板参数的泛型类:
template<uint8_t D>
class Tile
{
private:
uint8_t density = D;
public:
void someMethod()
{
if(D == 1)
{ /* do this */ }
else
{ /* do that */ }
}
};
根据模板参数D
,在对象的方法中采用特定的代码路径。对我来说,这样做的原因是,这使编译器能够完全优化掉 if
语句,因为 D
永远不会改变。对于外界,模板参数 D
根本不会改变对象的接口(interface)——无论 D
的值是多少,对象的接口(interface)都保持不变。
现在我想将这样一个对象传递给另一个方法,用它做一些事情。我将如何以一般方式做到这一点?
void processSomething(Tile *tile)
{
tile->someMethod();
}
这当然失败了,因为没有指定模板参数。然而,对于 Tile
的用户来说,模板参数没有任何区别,它仅用于内部状态。我如何编写 processSomething
,以便模板参数的值无关紧要?
我找到的唯一解决方案是像这样实现重载:
void processSomething(Tile<0> *tile);
void processSomething(Tile<1> *tile);
...
这是不切实际的。或者使 processSomething
本身成为模板,但随后我必须指定调用 processSomething
的值,这只会将问题转移给调用者。
最佳答案
您可以为该函数编写另一个模板:
template<uint8_t D>
void processSomething(Tile<D> *tile)
{
tile->someMethod();
}
关于c++ - 非类型模板参数 : pass to another method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49812527/