gpt4 book ai didi

c++通过模板实例化类

转载 作者:行者123 更新时间:2023-11-28 02:27:38 24 4
gpt4 key购买 nike

<分区>

有没有可能实现这样的目标?与其使用不同的函数来实例化不同的类,不如编写一个函数来实例化不同的类,如果它们从基类派生并采用相同的参数,那就太好了。

#include <iostream>
#include <string>
#include <vector>
#include <limits>

class Base
{
void DoSomething()
{
std::cout << "Oh yes" << std::endl;
}
};

class Derived1 : public Base
{

};

class Derived2 : public Base
{

};

template <typename T>
T* Create<T>()
{
return new T;
}

int main()
{
auto* test = Create<Derived1>();
test->DoSomething();
delete test;

std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
return 0;
}

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