关于C++模板的最重要的事情......经验教训

14 c++ templates

您对模板了解最重要的事项:隐藏功能,常见错误,最佳和最有用的实践,提示...... 常见错误/疏忽/假设

我开始使用模板实现我的大多数库/ API,并希望收集在实践中发现的最常见的模式,提示等.

让我正式化问题:你对模板学到的最重要的事情是什么?

请尝试提供示例 - 与更复杂和过于干燥的描述相比,它更容易理解

谢谢

Ale*_*x B 18

"Exceptional C++ style",第7项:函数重载解析模板专门化之前发生.不要混合模板函数的重载函数和特化,或者你在实际调用函数时遇到了令人讨厌的惊喜.

template<class T> void f(T t) { ... }   // (a)
template<class T> void f(T *t) { ... }  // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!
Run Code Online (Sandbox Code Playgroud)

第7项之上:

更糟糕的是,如果省略模板特化中的类型,则可能会根据定义的顺序使用不同的函数模板,因此可能调用或不调用专用函数.

情况1:

template<class T> void f(T t) { ... }  // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... }      // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called
Run Code Online (Sandbox Code Playgroud)

案例2:

template<class T> void f(T t) { ... }  // (a)
template<> void f(int *t) { ... }      // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called
Run Code Online (Sandbox Code Playgroud)


dic*_*oce 7

这可能不受欢迎,但我认为需要说.

模板很复杂.

它们非常强大,但明智地使用它们.不要太疯狂,不要有太多的模板参数......没有太多的专业化......记住,其他程序员也必须阅读这个.

最重要的是,远离模板元编程......


Dre*_*all 6

我不得不说Coplien的好奇重复模板模式(CRTP)是我发现自己一遍又一遍地接触的模板技巧.本质上,它允许您通过从派生类名参数化的基类继承,将静态自定义功能注入派生类.令人难以置信,但非常有用(有些人称之为静态多态).

此外,我将第二次看到Neil Butterworth的建议,阅读"C++模板",然后投入Alexandrescu的Modern C++ Design.


kyk*_*yku 5

每日模板提示:您知道吗,您可以专门化模板实例化的选定功能:

#include <iostream>
#include <vector>

namespace std {
    template<>
    void vector<int>::clear() {
    std::cout << "Clearing..." << std::endl;
    resize(0);
    }
}

int main() {
    std::vector<int> v;
    v.push_back(1);
    v.clear();
}
Run Code Online (Sandbox Code Playgroud)

输出:清除...