2017-12-14 3 views
0

auto 키워드의 사용이 최신 버전의 C++에서보다 효율적으로 처리되었다고 생각합니다. data type specifier없이 auto 이전에 서면 int로 기본 설정됩니다 :함수 오버로딩 대신`auto` 매개 변수를 사용하는 방법은 무엇입니까?

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

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

을 내가 할 수있는 14.0 ++ 새로운 MSVC에서 :

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; 
} 

. 함수 오버플로를 극복하고 싶었습니다. printauto 변수를 취합니다. 그러면 컴파일러를 호출하여 매개 변수의 관련 데이터 유형을 전달합니다.

하지만 컴파일시 얻을 문제 오류 :

A parameter cannot have type that have 'auto'. 

것은이 :이 프로그램은 gccIdeone 컴파일러에 잘 작동 : https://ideone.com/i3DKzl

+1

[좋은 책] (https://stackoverflow.com/a/388282/2069064)의 템플릿 섹션을 확인하십시오. – Barry

답변

0

기능 auto 매개 변수를 가질 수 없습니다. 대신 템플릿을 원합니다.

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