Instance value for templates

Please note that the code is generated only for called member functions. For class templates, member functions are only created when they are used.

The above quote from the book: C ++ Templates by Addison Wesley.

I want to understand the meaning of the dictionary "code is created." Does this mean that only a specific memory is reserved, or is this code only compiled or something else?

+5
source share
5 answers

, , . , . - ( ) .

, ( # generics, ++), , . ( , , ++), ( ), . Instantiation - , , , .

, , , , . , . (google ), , , , , . , -, , .

, . , , , . std::vector<int> v;, int ( std::allocator<int>) template std::vector std::vector<int>, -, , , std::vector<int>::vector() std::vector<int>::~vector(). .

-, . ( / - , , ). , - . , operator[] map , , , , , find insert, std::map , . -, , , , .

, , . , , - , (.. - -, ) -.

+6

, , - . , , , , .

, , , , , , , - . :

#include <stdio.h>
#include <string>

template<typename T>
struct Foo
{
    const T& x;

    Foo(const T& x) : x(x) {}

    template<typename S>
    operator S () const
    {
        S s;
        s = x + 1;
        return s;
    }
};

int main()
{
    std::string s = "bar";
    int i = 42;
    Foo<std::string> fs(s);
    Foo<int> fi(i);

    printf("Here we go... -> %f\n", double(fi));
    // printf("This won't compile -> %f\n", double(fs));
    return 0;
}

, Foo<std::string> double ( x+1 std::string).

, , .

+1

, , , , . , , , , .

0

. " " , ( ). , / .

( Referred , . , - . , , .)

,

template<typename T>
T add(T a, T b) { return a + b; }

, double as,

double d = add(2.3, 4.6);

add<double>(). add<int>() add<A>().

0

Instantiation. . .. / .

- , - () . ++, , .

, .

0

All Articles