功能模板与自动关键字

The*_*978 23 c++ templates auto

autoC++ 11中的关键字可以替换函数模板和特化吗?如果是,使用模板函数和特化而不是简单地键入函数参数有什么好处auto.如果没有,我完全期望被投入到地狱中,但我是C++的新手,但所以请放轻松我.

template <typename T>
void myFunction(T &arg)
{
    // ~
}
Run Code Online (Sandbox Code Playgroud)

void myFunction(auto &arg)
{
    // ~
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*eyn 9

简而言之,auto不能用于省略函数参数的实际类型,因此坚持使用函数模板和/或重载.auto在法律上用于自动推断变量的类型:

auto i=5;
Run Code Online (Sandbox Code Playgroud)

但是要非常小心地理解以下内容之间的区别:

auto x=...
auto &x=...
const auto &x=...
auto *px=...; // vs auto px=... (They are equivalent assuming what is being 
              //                 assigned can be deduced to an actual pointer.)
// etc...
Run Code Online (Sandbox Code Playgroud)

它还用于后缀返回类型:

template <typename T, typename U>
auto sum(const T &t, const U &u) -> decltype(t+u)
{
  return t+u;
}
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要概述 auto 在 99% 的情况下都很好,有时你必须停下来思考一下 auto 真正在做什么 http://stackoverflow.com/questions/12773257/does-auto-type- c11 中的指针赋值要求指针可能是 auto 的一个特殊情况。 (2认同)

Mik*_*our 6

autoC++ 11中的关键字可以替换函数模板和特化吗?

没有.有人建议将关键字用于此目的,但它不在C++ 11中,我认为C++ 14只允许它用于多态lambda,而不是函数模板.

如果是,使用模板函数和特化而不是简单地键入函数参数有什么好处auto.

如果要引用类型,您可能仍需要命名模板参数; 这比std::remove_reference<decltype(arg)>::type什么都方便.


小智 5

唯一使它auto与关键字不同的template是你不能使用关键字创建泛型类auto

class B { auto a; auto b; }
Run Code Online (Sandbox Code Playgroud)

当您创建上述类的对象时,它会给您一个错误。

B b; // Give you an error because compiler cannot decide type so it can not be assigned default value to properties
Run Code Online (Sandbox Code Playgroud)

而使用模板你可以创建一个像这样的通用类:

template <class T> 

class B {
    T a;
};

void main() {
    B<int> b; //No Error
}
Run Code Online (Sandbox Code Playgroud)