编译器是否基于模板实例化为CPP中的模板代码生成特定代码?

时间:2019-04-02 00:02:08

标签: c++

编译器是否为C ++中的模板代码生成特定的代码?例如如果为int实例化了模板,则编译器将生成int版本。我以为可以,但是在源代码的任何地方都看不到生成的代码?

Vehicle.h

#ifndef VEHICLE_H
#define VEHICLE_H

template <class T> 

class Vehicle
{

private:

    T m_x;
    T m_y;


public:
    static T val;
    Vehicle(T x, T y);

    Vehicle();

    ~Vehicle();

    T add();

};

#endif

Vehicle.cpp

#include <iostream>
#include "Vehicle.h"
#include <iostream>

template <class T>
Vehicle<T>::Vehicle(T x, T y): m_x(x), m_y(y)
{
    std::cout << "Parameterised constructor called" << std::endl;
}

template <class T>

Vehicle<T>::Vehicle()
{
    std::cout << "Calling default constructor" << std::endl;
}
template <class T>
Vehicle<T>::~Vehicle()
{
    std::cout << "Calling destructor" << std::endl;
}

template <class T>

T Vehicle<T>::add()
{
    return m_x + m_y;
}

现在,实例化特定代码的文件-

#include "Vehicle.cpp"

template class Vehicle<int>;
template class Vehicle<float>;

我正在使用Visual Studio编译和链接代码。阅读完模板后-https://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_122.html

0 个答案:

没有答案