如何使用`auto`参数而不是函数重载?

时间:2017-12-14 18:10:18

标签: c++ auto

我认为在最近的C ++版本中,关键字auto的使用变得更加高效。在没有auto的旧版data type specifier中,默认为int,所以写道:

auto value = 5.7; // implicit conversion to int
std::cout << value; // 5

auto val2 = "Hello there!"; // error: cannot convert from char* to int

在新的MSVC ++ 14.0中,我可以:

auto val = "Hello"; // val is of type char*
std::cout << val; // Hello

auto dVal = 567.235; // dVal is of type double. Ok

以上是如此好,这消除了负担得到泛型类型。

但请考虑这个例子:

#include <iostream>
using namespace std;

void print(auto param) { // error here:   A parameter cannot have type that contains 'auto' 
    cout << param << endl;
}

int main() {

    print("Hello!"); // string
    print(57); // int
    print(3.14); // double

    std::cout << std::endl;
    std::cin.get();
    return 0;
}

只要编译器根据输入值为我的变量选择正确的类型,我想要上面的内容。我想克服函数重载使函数print取一个auto变量,然后当我调用它时,编译器将传递参数的相关数据类型。

但问题是我得到编译时错误:

A parameter cannot have type that have 'auto'.

问题是:此程序适用于gccIdeone编译器:https://ideone.com/i3DKzl

1 个答案:

答案 0 :(得分:0)

不允许函数具有auto个参数。你想要一个模板。

template <class T>
void print(T&& param) {
    cout << param << endl;
}