Tim Reddy
Tim Reddy

Reputation: 4430

Unable to use a struct that uses a template as a parameter in a method

I have the following code:

template <typename A, typename B>
struct TheStruct {
    A a;
    B b;
};

class TheClass {
public:
    void do_something(TheStruct<A,B> blah);
}

I get compiler errors on the do_somethng method that resembles error: 'A' was not declared in this scope...

What is the correct syntax for defining this kind of type in a method parameter?

Thanks!

Upvotes: 0

Views: 99

Answers (3)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You'll need to either make TheClass a template:

template <typename A, typename B>
class TheClass {
public:
    void do_something(TheStruct<A,B> blah);
};

Or you'll need to make do_something() a template:

class TheClass {
public:
    template <typename A, typename B>
    void do_something(TheStruct<A,B> blah);
};

Upvotes: 2

Mark B
Mark B

Reputation: 96233

That depends. Do you want do_something to work on ANY version of TheStruct, or one specific one (for example where type A is int and B is double?

For the first case you'll need to make either TheClass or do_something ALSO a template (example grabbed from @PigBen):

template <typename A, typename B>
class TheClass {
public:
    void do_something(TheStruct<A,B> blah);
};

OR

class TheClass {
public:
    template <typename A, typename B>
    void do_something(TheStruct<A,B> blah);
};

If you just need to work with one specific instantiation of TheStruct then you specify the exact types:

class TheClass {
public:
    void do_something(TheStruct<int, double> blah);
}

Upvotes: 0

TonyK
TonyK

Reputation: 17114

A and B are just placeholders in the template definition. To make this clear: your template definition is semantically the same as

template <typename TotallyDifferentA, typename TotallyDifferentB>
struct TheStruct {
    TotallyDifferentA a;
    TotallyDifferentB b;
};

So it's not surprising that

void do_something(TheStruct<A,B> blah);

doesn't compile. A and B are not defined. This compiles:

class TheClass {
public:
    void do_something(TheStruct<int,void(*)(double,char*)> blah);
} ;

Upvotes: 0

Related Questions