简体   繁体   English

C ++访问变量而不使用其名称?

[英]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; 我的选择将是: Controller<Container> Glass; or Controller<Fruit> Apple; 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. 我现在的布局基本上是structsclassesYear()是每个函数。

I suppose the alternative is just to have static bool YearCompare(int year1, int year2) . 我想替代方法是只具有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. 编辑: Year()实际上是我在这里描述的一个更大的函数,因此不必继续重复它。

Since you say both structs have a Year() method, you can simply call that, eg: 由于您说两个结构都具有Year()方法,因此可以简单地调用它,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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