Nick Sweet
Nick Sweet

Reputation: 2139

Accessing a nonmember function of a derived class from a base class

I'm trying to call a nonmember function of a derived class from a base class, but getting this error:

error: no matching function for call to 'generate_vectorlist(const char&)'

Here's the relevant code snippets from the base class:

//Element.cpp
#include "Vector.h"
    ...

string outfile;
cin >> outfile;
const char* outfile_name = outfile.c_str();
generate_vectorlist(*outfile_name); //ERROR
...

and the derived class (this is a template class, so everything's in the header):

//Vector.h 
    template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )
{
    std::ofstream vectorlist(outfile_name);
    if (vectorlist.is_open())
        for (Element::vciter iter = Element::vectors.begin(); iter!=Element::vectors.end(); iter++) 
        {
            Vector<T>* a = new Vector<T>(*iter);
            vectorlist << a->getx() << '\t' << a->gety() << '\t'<< a->getz() << std::endl;
            delete a;
        }
    else { std::cout << outfile_name << " cannot be opened." << std::endl;}
    vectorlist.close();
}

My guess is there's just a small syntax thing that I'm missing. Any ideas?

Upvotes: 0

Views: 152

Answers (5)

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76611

You have two problems:

  1. generate_vectorlist takes a const char *, not a const char &.

  2. The template type is not in the function signature so the compiler can not deduce the type therefore you need to specify it (using int in my example).

So you need to do:

generate_vectorlist<int>(outfile_name);

Upvotes: 3

greyfade
greyfade

Reputation: 25677

This is the problem:

template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )

The compiler can't deduce the type of T, so it has no idea which generate_vectorlist to use.

Call it like this:

generate_vectorlist<vectortype>(outfile_name);

Though I would actually suggest that this code doesn't make any sense in the first place.

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62123

You need to specify the template argument. There's nothing the compiler can use to deduce what type T is. So you'll have to call it like generate_vectorlist<MyType>(outfile_name);, using the appropriate type for MyType.

Upvotes: 1

Reinderien
Reinderien

Reputation: 15338

In the first bit, try: generate_vectorlist(outfile_name);

You should be passing a character pointer, not a character.

Upvotes: 1

Gary
Gary

Reputation: 5732

You're dereferencing the pointer so you're passing a const char, not a const char*.

try this:

generate_vectorlist(outfile_name);

Upvotes: 3

Related Questions