开发者

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

开发者 https://www.devze.com 2023-02-09 23:56 出处:网络
I have the following code: template <typename A, typename B> struct TheStruct { A a; B b; }; class TheClass {

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 resemble开发者_Python百科s error: 'A' was not declared in this scope...

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

Thanks!


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消