Implicit Template Parameters

后端 未结 7 931
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 15:46

    Compiler can deduce the template argument such case:

    template
    void fun(T param)
    {
        //code...
    }
    
    fun(100);    //T is deduced as int;
    fun(100.0);  //T is deduced as double
    fun(100.0f); //T is deduced as float
    
    Foo foo(100);
    fun(foo);    //T is deduced as Foo;
    
    Foo bar('A');
    fun(bar);    //T is deduced as Foo;
    

    Actually template argument deduction is a huge topic. Read this article at ACCU:

    The C++ Template Argument Deduction

提交回复
热议问题