Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Candidate function not viable" from g++/gcc compiler. What is wrong here?

Tags:

c++

gcc

g++

I'm trying to compile my main.cpp, but I keep getting this error for two hours now. The issue here is to pass a function as a parameter but I think I'm doing something wrong. The compiler says it cannot find the function, but I included "newt_rhap(params)" in the "functions.h" already.

I did the returnType (*functionName)(paramType), but I may have skipped something here. The code of my friends doesn't need the recently mentioned syntax. What is wrong here?

I tried using both -std=c++11 and -std=c++98. The gcc/g++ compiler came from my Xcode command line tools.

g++ (or gcc) -std=c++98(or 11) main.cpp -o main.out

There was no difference in error.

**error: no matching function for call to 'newt_rhap'**

./functions.h:5:8: note: candidate function not viable: no known conversion from 'double' to
      'double (*)(double)' for 1st argument

double newt_rhap(double deriv(double), double eq(double), double guess);

Here is the code.

// main.cpp
#include <cmath>
#include <cstdlib>
#include <iostream>
#include "functions.h"

using namespace std;


// function declarations
// =============
// void test(double d);
// =============

int main(int argc, char const *argv[])
{
    //
    // stuff here excluded for brevity
    //

    // =============
    do
    {
        // line with error
        guess = newt_rhap(eq1(guess),d1(guess),guess);

        // more brevity

    } while(nSig <= min_nSig);
    // =============

    cout << "Root found: " << guess << endl;

    return 0;
}

Then functions.h and functions.cpp, respectively

// functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

// ===========
double newt_rhap(double deriv(double), double eq(double), double guess);
// ===========


// ===========
double eq1(double x);
double d1(double x);
// ===========


#endif

// functions.cpp
#include <cmath>
#include "functions.h"

using namespace std;

// ===========
double newt_rhap(double (*eq)(double ) , double (*deriv)(double ), double guess)
{
    return guess - (eq(guess)/deriv(guess));
}
// ===========

// ===========
double eq1(double x)
{
    return exp(-x) - x;
}

double d1(double x)
{
    return -exp(-x) - 1;
}
like image 236
Nogurenn Avatar asked Dec 03 '13 06:12

Nogurenn


2 Answers

Instead of:

guess = newt_rhap(eq1(guess),d1(guess),guess);

try:

guess = newt_rhap(eq1, d1, guess);

The function takes two functions and a guess as arguments. By passing eq1(guess) you are passing a double, not a function (the evaluated result of eq1 with an argument of guess)

like image 120
Sam Cristall Avatar answered Oct 15 '22 03:10

Sam Cristall


The signature of your function prototype in functions.h does not match the signature of the function you implement in functions.cpp.

like image 32
Patrick Sanan Avatar answered Oct 15 '22 04:10

Patrick Sanan