c – 在输出参数中使用auto

有没有办法在这种情况下使用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);

当然,只要你重载函数,这一切都会失败.

相关文章

首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代...
1. C语言定义1个数组的时候, 必须同时指定它的长度.例如:int...
C++的auto关键字在C+⬑新标准出来之前基本...
const关键字是用于定义一个不该被改变的对象,它的作用是告诉...
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...