Can the types of parameters in template functions be inferred?

时光毁灭记忆、已成空白 提交于 2020-01-24 10:47:04

问题


I'm writing some template functions in C++, but I'm not sure if it's possible to define a template function that infers the types of its parameters.

I tried to define a template with inferred parameter types, but this example won't compile:

template <auto>   
auto print_stuff(auto x, auto y) 
{ 
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}

It works when I give a unique name to each parameter type, but this seems somewhat redundant:

#include <iostream> 
#include <string>

template <class Redundant_1,class Redundant_2>   
auto print_stuff(Redundant_1 x, Redundant_2 y) 
{ 
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}

int main() 
{ 
    print_stuff(3,"Hello!");
    return 0; 
}

Is it possible to define a template with inferred parameter types instead of giving each type a unique name?


回答1:


You can dispense with the template-header and names for the parameter-types if your compiler supports concepts, which isn't generally enabled even if asking for experimental C++2a mode.
On gcc for example, it must be separately enabled with -fconcepts.

See live on coliru.

#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!");
    return 0; 
}

As an aside, avoid std::endl and use std::flush in the rare cases you cannot avoid costly manual flushing. Also, return 0; is implicit for main().



来源:https://stackoverflow.com/questions/56758349/can-the-types-of-parameters-in-template-functions-be-inferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!