When a compiler can infer a template parameter?

后端 未结 3 1130
予麋鹿
予麋鹿 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:17

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

    #include  
    #include 
    
    template    
    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  
    #include 
    
    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; 
    }
    

提交回复
热议问题