简体   繁体   中英

C++ Access variable without using its name?

Ok really not sure how to explain this, but I'll give it a try:

I'm trying to figure a way to access variables without using their name? I have two functions which perform the exact same thing, but for different variable names. It seems silly to me to have to have these two functions, just because one struct has the same type but different name?

Say I have a template class:

template<class T>
class Controller
{
private:
    T Object;
public:
    bool YearCompare(int year1)
    {
        if (Object.???? == year1)
            return 1;
        return 0;
    }
};

Say I have structs:

struct Container
{
    int BuildYear;
    int Volume;
};
struct Fruit
{
    int GrowthYear;
    string Name;
};

My options would then be: Controller<Container> Glass; or Controller<Fruit> Apple; .

I'd like to use the one function to return the year of whichever struct is used with the template class. Having to use two different functions in this situation would defeat the purpose of having a template class. The layout I have at the minute is basically the structs are classes and Year() is a function in each of them.

I suppose the alternative is just to have static bool YearCompare(int year1, int year2) .

I'm thinking it's not really possible.. Any help would be appreciated though, thanks.

Edit: Year() is actually a bigger function that what I'm describing here, hence the desire to not have to keep repeating it.

Since you say both structs have a Year() method, you can simply call that, eg:

bool YearCompare(int year1)
{
    return (Object.Year() == year1);
}

Otherwise, maybe define some adapters that return the appropriate year based on the struct type:

template<class T>
struct ControllerAdapter
{
};

template<class T, class Adapter = ControllerAdapter<T> >
class Controller
{
private:
    T Object;
public:
    bool YearCompare(int year1)
    {
        return (Adapter::GetYear(Object) == year1);
    }
};

...

struct Container
{
    int BuildYear;
    int Volume;
};

template<>
struct ControllerAdapter<Container>
{
    static int GetYear(const Container &c) { return c.BuildYear; }
};

struct Fruit
{
    int GrowthYear;
    string Name;
};

template<>
struct ControllerAdapter<Fruit>
{
    static int GetYear(const Fruit &f) { return f.GrowthYear; }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM