Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Template Parameters

The following code generates a compile error in Xcode:

template <typename T>
struct Foo
{
    Foo(T Value)
    {
    }
};

int main()
{
    Foo MyFoo(123);
    return 0;
}

error: missing template arguments before 'MyFoo'

Changing Foo MyFoo(123); to Foo<int> MyFoo(123); fixes the issue, but shouldn't the compiler be able to figure out the appropriate datatype?

Is this a compiler bug, or am I misunderstanding implicit template parameters?

like image 348
Maxpm Avatar asked Feb 09 '11 16:02

Maxpm


1 Answers

The constructor could in theory infer the type of the object it is constructing, but the statement:

Foo MyFoo(123);

Is allocating temporary space for MyFoo and must know the fully-qualified type of MyFoo in order to know how much space is needed.

If you want to avoid typing (i.e. with fingers) the name of a particularly complex template, consider using a typedef:

typedef std::map<int, std::string> StringMap;

Or in C++0x you could use the auto keyword to have the compiler use type inference--though many will argue that leads to less readable and more error-prone code, myself among them. ;p

like image 121
Jonathan Grynspan Avatar answered Sep 24 '22 09:09

Jonathan Grynspan