Arm*_*yan 265
简而言之,CRTP是指A类具有基类,它是A类本身的模板特化.例如
template <class T>
class X{...};
class A : public X<A> {...};
Run Code Online (Sandbox Code Playgroud)
这是奇怪的经常性的,不是吗?:)
现在,这给你带来了什么?这实际上使X模板能够成为其特化的基类.
例如,您可以像这样制作一个通用单例类(简化版)
template <class ActualClass>
class Singleton
{
public:
static ActualClass& GetInstance()
{
if(p == nullptr)
p = new ActualClass;
return *p;
}
protected:
static ActualClass* p;
private:
Singleton(){}
Singleton(Singleton const &);
Singleton& operator = (Singleton const &);
};
template <class T>
T* Singleton<T>::p = nullptr;
Run Code Online (Sandbox Code Playgroud)
现在,为了使任意A类成为单身,你应该这样做
class A: public Singleton<A>
{
//Rest of functionality for class A
};
Run Code Online (Sandbox Code Playgroud)
所以你看?单例模板假定它的任何类型X的特化将继承A
,因此可以访问其所有(公共,受保护)成员,包括A
!CRTP还有其他有用的用途.例如,如果你想要计算你的类当前存在的所有实例,但是想要将这个逻辑封装在一个单独的模板中(具体类的想法很简单 - 有一个静态变量,ctors增量,dtors减少) ).尝试做它作为一个练习!
另一个有用的例子,对于提升(我不确定他们是如何实现它的,但是CRTP也会这样做).想象一下,您只想为您的类提供<运算符<但是为它们自动运算符==!
你可以这样做:
template<class Derived>
class Equality
{
};
template <class Derived>
bool operator == (Equality<Derived> const& op1, Equality<Derived> const & op2)
{
Derived const& d1 = static_cast<Derived const&>(op1);//you assume this works
//because you know that the dynamic type will actually be your template parameter.
//wonderful, isn't it?
Derived const& d2 = static_cast<Derived const&>(op2);
return !(d1 < d2) && !(d2 < d1);//assuming derived has operator <
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样使用它
struct Apple:public Equality<Apple>
{
int size;
};
bool operator < (Apple const & a1, Apple const& a2)
{
return a1.size < a2.size;
}
Run Code Online (Sandbox Code Playgroud)
现在,你没有为apple明确提供operator ==?但你拥有它!你可以写
int main()
{
Apple a1;
Apple a2;
a1.size = 10;
a2.size = 10;
if(a1 == a2) //the compiler won't complain!
{
}
}
Run Code Online (Sandbox Code Playgroud)
如果你只是为Apple编写operator ==,你可能会写得更少,但想象Equality模板不仅会提供==而且>,> =,<=等等.你可以将这些定义用于多个类,重用代码!
CRTP是一件很棒的事情:HTH
Gut*_*Mac 44
在这里你可以看到一个很好的例子.如果使用虚方法,程序将知道在运行时执行什么.实现CRTP编译器是在编译时决定的!这是一个很棒的表现!
template <class T>
class Writer
{
public:
Writer() { }
~Writer() { }
void write(const char* str) const
{
static_cast<const T*>(this)->writeImpl(str); //here the magic is!!!
}
};
class FileWriter : public Writer<FileWriter>
{
public:
FileWriter(FILE* aFile) { mFile = aFile; }
~FileWriter() { fclose(mFile); }
//here comes the implementation of the write method on the subclass
void writeImpl(const char* str) const
{
fprintf(mFile, "%s\n", str);
}
private:
FILE* mFile;
};
class ConsoleWriter : public Writer<ConsoleWriter>
{
public:
ConsoleWriter() { }
~ConsoleWriter() { }
void writeImpl(const char* str) const
{
printf("%s\n", str);
}
};
Run Code Online (Sandbox Code Playgroud)
blu*_*kin 20
CRTP是一种实现编译时多态性的技术.这是一个非常简单的例子.在下面的示例中,ProcessFoo()
正在使用Base
类接口并Base::Foo
调用派生对象的foo()
方法,这是您要用虚拟方法执行的操作.
http://coliru.stacked-crooked.com/a/2d27f1e09d567d0e
template <typename T>
struct Base {
void foo() {
(static_cast<T*>(this))->foo();
}
};
struct Derived : public Base<Derived> {
void foo() {
cout << "derived foo" << endl;
}
};
struct AnotherDerived : public Base<AnotherDerived> {
void foo() {
cout << "AnotherDerived foo" << endl;
}
};
template<typename T>
void ProcessFoo(Base<T>* b) {
b->foo();
}
int main()
{
Derived d1;
AnotherDerived d2;
ProcessFoo(&d1);
ProcessFoo(&d2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
derived foo
AnotherDerived foo
Run Code Online (Sandbox Code Playgroud)
同样注意:
CRTP可用于实现静态多态性(类似于动态多态,但没有虚函数指针表).
#pragma once
#include <iostream>
template <typename T>
class Base
{
public:
void method() {
static_cast<T*>(this)->method();
}
};
class Derived1 : public Base<Derived1>
{
public:
void method() {
std::cout << "Derived1 method" << std::endl;
}
};
class Derived2 : public Base<Derived2>
{
public:
void method() {
std::cout << "Derived2 method" << std::endl;
}
};
#include "crtp.h"
int main()
{
Derived1 d1;
Derived2 d2;
d1.method();
d2.method();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出将是:
Derived1 method
Derived2 method
Run Code Online (Sandbox Code Playgroud)
这不是直接的答案,而是CRTP如何有用的一个示例。
的一个很好的具体的例子CRTP是std::enable_shared_from_this
从C ++ 11:
类
T
可以继承自来enable_shared_from_this<T>
继承shared_from_this
获得shared_ptr
指向的实例的成员函数*this
。
也就是说,继承自std::enable_shared_from_this
可以在不访问实例的情况下获得指向您实例的共享(或弱)指针(例如,从您仅了解的成员函数中*this
)。
当您需要给一个,std::shared_ptr
但您只能访问时,这很有用*this
:
struct Node;
void process_node(const std::shared_ptr<Node> &);
struct Node : std::enable_shared_from_this<Node> // CRTP
{
std::weak_ptr<Node> parent;
std::vector<std::shared_ptr<Node>> children;
void add_child(std::shared_ptr<Node> child)
{
process_node(shared_from_this()); // Shouldn't pass `this` directly.
child->parent = weak_from_this(); // Ditto.
children.push_back(std::move(child));
}
};
Run Code Online (Sandbox Code Playgroud)
您不能直接通过this
而不是直接通过的原因shared_from_this()
是,它将破坏所有权机制:
struct S
{
std::shared_ptr<S> get_shared() const { return std::shared_ptr<S>(this); }
};
// Both shared_ptr think they're the only owner of S.
// This invokes UB (double-free).
std::shared_ptr<S> s1 = std::make_shared<S>();
std::shared_ptr<S> s2 = s1->get_shared();
assert(s2.use_count() == 1);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42339 次 |
最近记录: |