如何使用指向通用模板类的指针来访问依赖于模板参数类型的成员函数

How to use a pointer to a generic template class to access a member function that depends on the template parameter type

本文关键字:访问 依赖于 参数 函数 成员 类型 何使用 指针      更新时间:2023-10-16

有没有一种方法可以让指针指向通用模板类并调用返回值取决于模板参数的函数?以下是我要做的:

class Node{...}
template < typename Type > class NumberNode : public Node
{
    public:
        NumberNode( Type value ) : _value( value ) { }
        Type getValue() { return _value; }
    private:
        Type _value;
}
void foo( int x )    { /* do something */ }
void foo( float x )  { /* do something else */ }
void main(...)
{
    std::vector< Node* > nodes;
    nodes.push_back( new NumberNode< int >( 1 ) );
    nodes.push_back( new NumberNode< float >( 1.f ) );
    for( Node* ptr_node : nodes )
    {
        foo( static_cast< NumberNode* >( ptr_node )->getValue() );
    }
}

我不能这样做,因为static_cast( Derived* )应该知道完整的模板类型,这是不同的。我也不能将Base作为模板类型,因为其他类也从中派生。有人知道解决方法吗?

这是正确的做法:

class Node 
{
 public:
  virtual void foo() = 0;
};

你的循环变成

for( Node* ptr_node : nodes )
{
    ptr_node->foo();
}

foo可以在NumberNode中实现,如下所示:

template <typename Type> 
void NumberNode::foo() 
{
  ::foo(_value);
}

也许这个设计不再需要getValue(),你可以去掉它。这是一件好事。吸气剂是设计薄弱的表现。对象应该的东西,而不是东西。

如果您出于某种原因不想在Node中使用foo(也许您有太多像foo这样的函数,并且不想污染接口),那么另一种方法是为Node实现VISITOR模式。然而,Visitor也有自己的缺点,所以我只建议在这种情况下将其作为最后的手段。