When a compiler can infer a template parameter?

后端 未结 3 1120
予麋鹿
予麋鹿 2020-12-08 04:53

Sometimes it works sometimes not:

template  
void f(T t) {}

template 
class MyClass {
public:
  MyClass(T t) {}
};

void test          


        
相关标签:
3条回答
  • 2020-12-08 05:11

    Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters

    So it can be inferred here:

    template <typename T>
    void f(T t);
    
    template <typename T>
    void f(std::vector<T> v);
    

    but not here:

    template <typename T>
    T f() {
      return T();
    }
    

    And not in class templates.

    So the usual solution to your problem is to create a wrapper function, similar to the standard library function std::make_pair:

      template <class T>
        class MyClass {
        public:
            MyClass(T t) {}
            void print(){
                std::cout<<"try MyClass"<<std::endl;
            }
        };
    
        template <typename T>
        MyClass<T> MakeMyClass(T t) { return MyClass<T>(t); }
    

    and then call auto a = MakeMyClass(5); to instantiate the class.

    0 讨论(0)
  • 2020-12-08 05:11

    Read up on Template Argument Deduction (and ADL or Koenig lookup).

    0 讨论(0)
  • 2020-12-08 05:17

    In C++17, it is possible to infer some types using auto, though the template parameters still need to be specified here:

    #include <iostream> 
    #include <string>
    
    template <class T1,class T2>   
    auto print_stuff(T1 x, T2 y) 
    { 
        std::cout << x << std::endl;
        std::cout << y << std::endl;
    }
    
    int main() 
    { 
        print_stuff(3,"Hello!");
        print_stuff("Hello!",4);
        return 0; 
    }
    

    Using the -fconcepts flag in gcc, it is possible to infer the parameters, though this is not yet a part of the C++ standard:

    #include <iostream> 
    #include <string>
    
    auto print_stuff(auto x, auto y) 
    { 
        std::cout << x << std::endl;
        std::cout << y << std::endl;
    }
    
    int main() 
    { 
        print_stuff(3,"Hello!");
        print_stuff("Hello!",4);
        return 0; 
    }
    
    0 讨论(0)
提交回复
热议问题