是否可以编写C++基类成员函数来实例化从中调用它的任何派生类?
Can a C++ base class member function be written to instantiate whatever derived class it's called from?
有没有任何方法可以在基类中实现一次函数,该函数将返回从中调用的任何派生类的实例?
template <class TDerived> class Base
{
TDerived retInstance()
{
return TDerived();
}
};
class Derived : Base<Derived>
{
//class definition here
};
如果您选择的语言支持协变返回类型,您可以执行类似于以下C++代码示例的操作:
struct A {
virtual A *make() = 0;
};
struct B : public A {
B *make() override {
return new B{};
}
};
虽然这不符合在基类中定义一次的标准,但我认为值得一提。
如前所述,
-
CRTP(奇怪的循环模板模式)
-
或可克隆模式。
1.CRTP
在Coliru上查看Liv
template <typename Derived>
struct BaseImpl
{
// normal stuff
int foo() const { return 42; }
// CRTP stuff
Derived make_new() const
{
return Derived("test 123");
}
};
#include <string>
struct MyStruct : BaseImpl<MyStruct>
{
std::string value;
MyStruct(std::string const& value) : value(value) {}
};
#include <iostream>
int main()
{
MyStruct a("first");
MyStruct b = a.make_new();
std::cout << a.value << "n"
<< b.value << "n";
}
打印
first
test 123
2.可克隆模式:
看到它在Coliru上直播太
struct ICloneable
{
virtual const char* whoami() const = 0;
virtual ICloneable* clone() const = 0;
virtual ~ICloneable() throw() {}
};
#include <string>
struct A : ICloneable
{
virtual const char* whoami() const { return "struct A"; }
virtual ICloneable* clone() const { return new A; }
};
struct B : ICloneable
{
virtual const char* whoami() const { return "struct B"; }
virtual ICloneable* clone() const { return new B; }
};
#include <iostream>
#include <typeinfo>
int main()
{
A a;
B b;
ICloneable* aclone = a.clone();
ICloneable* bclone = b.clone();
std::cout << typeid(*aclone).name() << "n";
std::cout << typeid(*bclone).name() << "n";
delete aclone;
delete bclone;
}
打印(取决于编译器):
1A
1B
相关文章:
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 如何从Windows控制台调用.exe(C++)以在不同的目录(或任何目录)中创建文件夹?
- VkSurfaceKHR 指针的值在函数调用后更改,无需任何显式赋值
- 在将匿名对象作为参数传递时,不会调用任何构造函数
- 如何推广下面的模板类以调用任何函数?
- 库路径绝对是正确的,可以创建所述库的实例,但在调用任何函数时"Undefined reference"
- 使用std ::函数在对象列表上调用任何对象成员函数
- 来自没有默认构造函数的超级类的子类,而无需调用任何其他构造函数
- 可以在 main 的返回 0 语句之后调用任何函数吗?
- 不调用任何与窗口相关的函数
- 为什么std::vector::template在没有调用任何复制构造函数的情况下调用析构函数
- C++:创建一个可以调用任何函数的计时器/警报类
- 调用任何入队命令时打开CL CL_INVALID_COMMAND_QUEUE
- 谷歌模拟:我怎么能" EXPECT "不会在模拟上调用任何方法
- 无法使用 devIL 调用任何函数
- 函数调用任何指定的函数
- 调用任何 cURL 函数都会导致在执行程序时"entry point not found"