c++类型推导

发布时间 2023-04-03 19:54:50作者: _Explosion!

传统c和c++中,无论什么变量都应该先去声明其类型,指出其类型后才能进行下一步操作,这通常会花费很多无意义的时间。

c++11引入了auto 和 decltype 这两个关键字实现了类型推导,让编译器来操心变量的类型。这使得 C++ 也具有了和其他现代编程语言一样,某种意义上提供了无需操心变量类型的使用习惯。

auto

auto关键字可以对一些变量进行类型推导,简单使用样例如下:

int a=10;
auto b=a;

我们经常在对迭代器或循环中的变量声明中使用它,如

set<int> a;
... for(auto it
= a.begin();it != a.end();++it){...} vector<int>b; ... for(auto num:b){...}

decltype

decltype关键字可以对一些表达式类型进行推导,例如:

auto x=1;    //x被推导为int
auto y=2;
decltype(x+y) z;    //z被推导为int
if (std::is_same<decltype(x), int>::value)
    std::cout << "type x == int" << std::endl;    //对x的类型进行判断

尾返回类型推导

c++11支持对函数返回类型进行推导,方法如下所示:

template<typename T, typename U>
auto add2(T x, U y) -> decltype(x+y){
    return x + y;
}

我们甚至可以配合std::future访问异步操作结果来实现对函数类型的推导(线程池中常见):

template <typename F, typename... Args>
    auto submit(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>
    {
        using return_type = decltype(f(args...));
        auto task_ptr = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        auto task_future = task_ptr->get_future();
        auto wrapper_func = [task_ptr]() { (*task_ptr)(); };
        schedule_by_id(std::move(wrapper_func));
        return task_future;
    }

注意上述函数返回的是一个std::future对象即期约对象,对返回对象使用get方法即可获取函数 f 即decltype(std::forward<F>(f)(std::forward<Args>(args)...))类型的结果。