Creating a C ++ instance, what exactly does this mean?

Now I am familiar with templates, and I am a little familiar with things like SFINAE, and I was wondering what happens when a template is instantiated by the compiler.

When you do something in TMP, like SFINAE, or even in a simple Fibonacci sequence in TMP, it looks like the compiler does more than what I understand when creating the template. It seems that the compiler is executing the template code.

My question is: what is instantiating the template, and where is the line drawn with the compiler actually executing the code?

The compiler creates the type of your template, this is my understanding of creating a template instance. But in TMP, it seems that he does a lot more than that, and that bothers me.

+3
source share
1 answer

It’s best to think of it as a bunch of functions, which is actually the case. Consider a class Typethat here represents the internal representation of a type compiler.

template<typename T> class X {
    T t;
};

At runtime, C ++ you can express it as

Type* X(Type *t) {
    static std::unordered_map<Type*, Type*> cache;
    if (cache.find(t) != cache.end())
        return cache[t];
    Type* ret = new Type;
    ret->DataMembers.insert("t", t);
    return cache[t] = ret;
}

Of course, specializations and the like will require a little more. Using this model, however, is easy for two things.

A) Creating an instance of a template is equivalent to calling a function that happens at compile time, just like constexpr. Of course, a smart compiler can do something else as an optimization, but in the general case.

B) How it applies to any other functions provided by the templates.

Turing, - . , , , - , . , EDSL .

+3

All Articles