Problem with auto c++11 feature

Hi friends,

Whilst trying auto feature, am hitting this following issue:

My code:
#include <iostream>
#include <math.h>

auto new_func(auto num){

return pow(num, 0.5) ;
}

int main(int argC, char* argV[]){

float num(0) ;
std::cout<<"Square root function !\nEnter a number: " ;
std::cin>>num ;
std::cout<<"Square root of "<<num<<" = "<<my_func(num)<<std::endl ;

return 0 ;
}

Error:
./First_go.cpp:10:20: error: parameter declared ‘auto’
auto new_func(auto num){
^
./First_go.cpp:10:23: warning: ‘new_func’ function uses ‘auto’ type specifier without trailing return type [enabled by default]
auto new_func(auto num){
^
./First_go.cpp: In function ‘auto new_func()’:
./First_go.cpp:12:16: error: ‘num’ was not declared in this scope
return pow(num, 0.5) ;

How to resolve this issue, why is this complaining, why cant it make num auto ? ??

Many Thanks,
San
How to resolve this issue, why is this complaining, why cant it make num auto ? ??


Because that's the job of templates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <math.h>

template <typename T>
auto my_func(T num) -> decltype(pow(num,0.5))
{
    return pow(num, 0.5);
}

int main(int argC, char* argV[]){

    float num(0);
    std::cout << "Square root function !\nEnter a number: ";
    std::cin >> num;
    std::cout << "Square root of " << num << " = " << my_func(num) << std::endl;

    return 0;
}


In C++14 you'll be able to leave out the trailing return type and let the compiler deduce the return type.
Wow amazing solution, tnx @cire
Thanks for the link @lsk

:)
You don't need to use auto for that, my_func could return T.
You don't need to use auto for that, my_func could return T.

How would my_func(2) work out if you did that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <math.h>

template <typename T>
auto my_func(T num) -> decltype(pow(num,0.5))
{
    return pow(num, 0.5);
}

template <typename T>
T f(T num)
{
    return pow(num, 0.5);
}

int main(int argC, char* argV[]){

    float num(0);
    std::cout << "Square root function !\nEnter a number: ";
    std::cin >> num;
    std::cout << "Square root of " << num << " = " << my_func(num) << std::endl;
    std::cout << "Square root of " << num << " = " << f(num) << std::endl;
    std::cout << "Square root of " << num << " = " << f(1) << std::endl;
    std::cout << "Square root of " << num << " = " << f(1L) << std::endl;
    std::cout << "Square root of " << num << " = " << f(1.0) << std::endl;

    return 0;
}
haha ya tats true n easy tnx kbw, but I wanted to exclusively try some c++11 features ;)
Topic archived. No new replies allowed.