有没有办法在这种情况下使用auto关键字:
void foo(bar& output){ output = bar(); } int main(){ //Imaginary code auto a; foo(a); }
当然,不可能知道什么类型的.因此,解决方案应该是以某种方式将它们合并为一个句子.这可用吗?
解决方法
看起来您希望默认初始化给定函数期望作为参数的类型的对象.
您无法使用auto执行此操作,但您可以编写一个特征来提取函数所需的类型,然后使用它来声明您的变量:
namespace detail { //expects the argument number and a function type template <std::size_t N,typename Func> struct arg_n; //does all the work template <std::size_t N,typename Ret,typename... Args> struct arg_n <N,Ret (Args...)> { using type = std::remove_reference_t< std::tuple_element_t<N,std::tuple<Args...>> >; }; } //helper to make usage neater template <std::size_t N,typename Func> using arg_n = typename detail::arg_n<N,Func>::type;
然后你就像这样使用它:
//type of the first argument expected by foo arg_n<0,decltype(foo)> a{}; foo(a);
当然,只要你重载函数,这一切都会失败.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。