user350814
user350814

Reputation:

Automatically inserted Template arguments?

A few days I literally discovered a behaviour of C++, where template arguments are automatically inserted, as shown in this example (nonsensical, only used to show what I mean):

#include <iostream>

template<typename Type> void setVar(Type& subj, const Type& in)
{
    subj = static_cast<Type>(in);
}

int main()
{
    int foo;
    setVar(foo, 42);
    std::cout << foo << std::endl;
}

My questions:

Upvotes: 2

Views: 143

Answers (2)

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

What is this behaviour called?

Template argument deduction.

are there special rules when and why templates can be automatically inserted?

You cannot say like templates are inserted. Rather the types of parameters are automatically deduced from the arguments. When and how? That's what TAD is all about.

Check out section 14.8.2 in C++03

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279255

It's called template argument deduction, and of course there are special rules. Many rules. In 14.8.2 of the standard [temp.deduct].

The summary version is that if there's a set of template arguments which allows the function to be called, then it will be called with those arguments. The complication is exactly what's allowed, and how to choose between possible alternatives.

Upvotes: 0

Related Questions