#include <iostream>
#include <type_traits>
using namespace std;
namespace
{
class IAnimal
{
public:
virtual void say() = 0;
};
class Dog : IAnimal
{
public:
void say() override
{
cout << "我是 狗!!" << '\n';
}
};
class Cat : IAnimal
{
public:
void say() override
{
cout << "我是 猫!!" << '\n';
}
};
class Horse
{
public:
void say()
{
cout << "我是 马!!" << '\n';
}
};
}
template <typename T,
typename = typename std::enable_if<std::is_base_of<IAnimal, T>::value>::type>
class MyPet
{
public:
void sayWhat()
{
m_pet.say();
}
private:
T m_pet;
};
int main()
{
MyPet<Dog> myDog;
myDog.sayWhat();
MyPet<Cat> myCat;
myCat.sayWhat();
// 放开注释 typename = typename std::enable_if ... ::type> type 会找不到而报错
/* MyPet<Horse> myHorse;
myHorse.sayWhat();*/
system("pause");
return EXIT_SUCCESS;
}
输出:
我是 狗!!
我是 猫!!
template <typename T,
typename = typename std::enable_if<std::is_base_of<IAnimal, T>::value>::type>
class MyPet
{
}
is_base_of
为 true 会展开成:
template <typename T,
typename = void
class MyPet
{
}
is_base_of
为 false 时会找不到 Type
而报错。
参考:https://blog.csdn.net/m0_60259364/article/details/129965365
标签:MyPet,限定,C++,public,say,sayWhat,type,class,模板 From: https://www.cnblogs.com/huvjie/p/18403354