如何使用指向通用模板类的指针来访问依赖于模板参数类型的成员函数
How to use a pointer to a generic template class to access a member function that depends on the template parameter type
有没有一种方法可以让指针指向通用模板类并调用返回值取决于模板参数的函数?以下是我要做的:
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也有自己的缺点,所以我只建议在这种情况下将其作为最后的手段。
相关文章:
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 为什么内存屏障依赖于变量?
- 反转依赖于 end() 的迭代器
- 编译依赖于 QTCore 库的 WASM
- 如何添加依赖于类本身的模板成员变量
- 初始化依赖于子类的继承类的常量类成员
- Makefile 创建两个库 - 一个依赖于另一个
- 对于BTreeMap和其他依赖于Ord的东西,是否有等效于C++比较器对象?
- 类成员函数参数列表是否可以依赖于模板参数?
- 依赖于类成员属性的类实例成员
- 如何定义依赖于参数包转换的函数的返回类型
- 依赖于模板的错误
- 依赖于特定类类型的C++模板方法
- FBString 的小字符串优化是否依赖于未定义的行为?
- CMake:如何在Visual Studio环境中将依赖于模式的编译标志传递给nvcc
- C++ 使函数调用依赖于模板参数
- 如何初始化依赖于先前条目的可变参数模板?
- cmake:构建依赖于非源文件.Qt帮助生成
- 如何修复"没有依赖于模板参数的参数'glGenVertexArrays'......"C++ 中的错误
- 如何使用指向通用模板类的指针来访问依赖于模板参数类型的成员函数