Implicit Template Parameters

后端 未结 7 930
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 15:00

The following code generates a compile error in Xcode:

template 
struct Foo
{
    Foo(T Value)
    {
    }
};

int main()
{
    Foo MyFoo(123);         


        
7条回答
  •  梦毁少年i
    2021-02-07 15:47

    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 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

提交回复
热议问题