gpt4 book ai didi

c++是否可以将对象类型传递给要与之比较的函数

转载 作者:太空狗 更新时间:2023-10-29 23:32:32 26 4
gpt4 key购买 nike

我遇到这样一种情况,我需要查明派生对象是否存储在另一个对象的 vector 中,并想对其进行功能化。我想不出一种方法来做我想做的事情,或者确定它是否可行。我有一个有效的解决方案,我将其包括在内,但如果有一种直接的方法来实现目标,它会更清晰。

这基本上就是我想做的:

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 );
}

这是实现目标的解决方法,但它有提供回调的额外步骤,我很想根除它:

#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 );
}

最佳答案

您不能将类型作为运行时函数参数传递,但可以将类型用作函数模板的编译时模板参数:

#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";
}
}

关于c++是否可以将对象类型传递给要与之比较的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37475097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com