C++ Templates

【C++ Templates(9)】模板实战

2018-04-24  本文已影响41人  downdemo

包含模型

// basics/myfirst.hpp

#ifndef MYFIRST_HPP
#define MYFIRST_HPP

// declaration of template
template<typename T>
void printTypeof (T const&);

#endif   //MYFIRST_HPP


// basics/myfirst.cpp

#include <iostream>
#include <typeinfo>
#include "myfirst.hpp"

// implementation/definition of template
template<typename T>
void printTypeof (T const& x)
{
    std::cout << typeid(x).name() << '\n';
}

// basics/myfirstmain.cpp

#include "myfirst.hpp"

// use of the template
int main()
{
    double ice = 3.0;
    print_typeof(ice); // call function template for type double
}
// basics/myfirst2.hpp

#ifndef MYFIRST_HPP
#define MYFIRST_HPP

#include <iostream>
#include <typeinfo>

// declaration of template
template<typename T>
void printTypeof (T const&);

// implementation/definition of template

template<typename T>
void printTypeof (T const& x)
{
    std::cout << typeid(x).name() << '\n';
}

#endif   //MYFIRST_HPP

显式实例化

template void print_typeof<double>(double const&);
// 基于int显式实例化函数模板max()
template int const& max(int const&, int const&);
// 基于int显式实例化的MyClass构造函数
template MyClass<int>::MyClass();
// 对于前面已经显式实例化过的成员函数不能再次显式实例化
template MyClass<std::string>::MyClass(); // 错误
template<typename T>
void f(T, T)
{}

template void f<double>(double, double); // 显式实例化

f(1, 1.2); // 错误:仍调用非实例化的原始版本,推断类型不一致
f(1.2, 1.2); // OK
f(1, 1); // OK

整合包含模型和显式实例化

// stack.hpp
#ifndef STACK_HPP
#define STACK_HPP

#include <vector>

template <typename T>
class Stack {
private:
    std::vector<T> elems;
public:
    Stack();
    void push(T const&);
    void pop();
    T top() const;
};


// stackdef.hpp
#ifndef STACKDEF_HPP
#define STACKDEF_HPP

#include "stack.hpp"
void Stack<T>::push(T const& elem)
{
    elem.push_back(elem);
}
...

#endif
// 显式实例化
// stacktest1.cpp
#include "stack.hpp"
#include <iostream>
#include <string>

int main()
{
    Stack<int> intStack;
    intStack.push(42);
    std::cout << intStack.top() << std::endl;
    intStack.pop();

    Stack<std::string> stringStack;
    stringStack.push("hello");
    std::cout << stringStack.top() << std::endl;
}


// 包含模型
// stack_inst.cpp
#include "stackdef.hpp"
#include <string>

// instantiate class Stack<> for int
template Stack<int>;

// instantiate member functions of Stack<> for strings
template Stack<std::string>::Stack();
template void Stack<std::string>::push(std::string const&);
template std::string Stack<std::string>::top() const;

分离模型(已淘汰)

// 头文件
#ifndef MYFIRST_HPP
#define MYFIRST_HPP

export
template <typename T>
void print_typeof(T const&);

#endif

模板和内联

template <typename T>
inline T min(const T&, const T&);

预编译头文件

上一篇 下一篇

猜你喜欢

热点阅读