jgi*_*bbs 2 c++ polymorphism typeid typeinfo
我有一种情况,我需要找出派生对象是否存储在另一个对象中的向量中,并希望将其功能化.我无法找到一种方法来做我想要的,或确定是否可能.我有一个可行的解决方案,但是如果有直接的方法来实现目标,它会更清晰.
这基本上就是我想做的事情:
class IFruit
{
public:
virtual ~IFruit(){};
};
class Apple : public IFruit {};
class Banana : public IFruit {};
class Orange : public IFruit {};
class FruitBowl
{
public:
bool HasFruit( datatype?? FruitType )
{
for ( auto iter : m_Fruit )
{
if ( typeof( iter ) == typeof( FruitType ) )
{
return ( true );
}
}
return ( false );
}
vector< IFruit* > m_Fruit;
};
int main()
{
FruitBowl Snacks;
Snacks.m_Fruit.push_back( new Banana );
Snacks.m_Fruit.push_back( new Apple );
Snacks.m_Fruit.push_back( new Orange );
if ( Snacks.HasFruit( Orange ) )
{
cout << "There is an orange available";
}
return ( 0 );
}
Run Code Online (Sandbox Code Playgroud)
这是一个实现目标的解决方法,但它提供了额外的步骤来提供我想要根除的回调:
#include <vector>
#include <iostream>
#include <functional>
using namespace std;
class IFruit
{
public:
virtual ~IFruit(){};
};
class Apple : public IFruit {};
class Banana : public IFruit {};
class Orange : public IFruit {};
class FruitBowl
{
public:
bool HasFruit( function< bool( IFruit* ) > fnCompareFruitType )
{
for ( auto iter : m_Fruit )
{
if ( fnCompareFruitType( iter ) )
{
return ( true );
}
}
return ( false );
}
vector< IFruit* > m_Fruit;
};
int main()
{
FruitBowl Snacks;
Snacks.m_Fruit.push_back( new Banana );
Snacks.m_Fruit.push_back( new Apple );
Snacks.m_Fruit.push_back( new Orange );
if ( Snacks.HasFruit( []( IFruit* TestFruit ){ return ( dynamic_cast< Orange* >( TestFruit ) != nullptr ); } ) )
{
cout << "There is an orange available";
}
return ( 0 );
}
Run Code Online (Sandbox Code Playgroud)
您不能将类型作为运行时函数参数传递,但可以使用一个作为函数模板的编译时模板参数:
#include <vector>
#include <iostream>
#include <algorithm>
class IFruit
{
public:
virtual ~IFruit(){};
};
class Apple : public IFruit {};
class Banana : public IFruit {};
class Orange : public IFruit {};
class FruitBowl
{
public:
template <typename T>
bool HasFruit()
{
return std::any_of(m_Fruit.begin(), m_Fruit.end(),
[](IFruit* fruit) {
return dynamic_cast<T*>(fruit) != nullptr;
});
}
std::vector< IFruit* > m_Fruit;
};
int main()
{
FruitBowl Snacks;
Snacks.m_Fruit.push_back( new Banana );
Snacks.m_Fruit.push_back( new Apple );
Snacks.m_Fruit.push_back( new Orange );
if ( Snacks.HasFruit<Orange>() )
{
std::cout << "There is an orange available";
}
}
Run Code Online (Sandbox Code Playgroud)