Implicit Template Parameters

后端 未结 7 937
佛祖请我去吃肉
佛祖请我去吃肉 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:36

    compiler can figure out template parameter type only for templated functions, not for classes/structs

    0 讨论(0)
  • 2021-02-07 15:41

    In C++11 you can use decltype:

    int myint = 123;
    Foo<decltype(myint)> MyFoo(myint);
    
    0 讨论(0)
  • 2021-02-07 15:41

    It's not a bug, it's non-existing feature. You have to fully specify class/structure template arguments during instantiation, always, the types are not inferred as they can be for function templates.

    0 讨论(0)
  • 2021-02-07 15:46

    Compiler can deduce the template argument such case:

    template<typename T>
    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<int> foo(100);
    fun(foo);    //T is deduced as Foo<int>;
    
    Foo<char> bar('A');
    fun(bar);    //T is deduced as Foo<char>;
    

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

    The C++ Template Argument Deduction

    0 讨论(0)
  • 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<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

    0 讨论(0)
  • 2021-02-07 15:47

    It makes a lot of sense it is like this, as Foo is not a class, only Foo<T> where T is a type.

    In C++0x you can use auto, and you can create a function to make you a Foo, let's call it foo (lower case f). Then you would do

    template<typename T> Foo<T> foo(int x)
    {
      return Foo<T>(x);
    }
    
    auto myFoo = foo(55);
    
    0 讨论(0)
提交回复
热议问题