gpt4 book ai didi

保存类模板的任何特化的 C++ 变量

转载 作者:太空狗 更新时间:2023-10-29 20:22:40 26 4
gpt4 key购买 nike

我需要能够将模板的任何特化存储在变量中,例如:

template<T>
class Grid {
int GetRows();
int GetTypeOfColumn(int col);
//...etc...
}

//EDIT:
Grid<int>::GetTypeofColumn(int col) {
return col == 0 ? STRING_COL_TYPE : INT_COL_TYPE;
}
Grid<string>::GetTypeofColumn(int col) {
return STRING_COL_TYPE;
}
//End EDIT

class Foo {
Grid<int>* aBunchOfNumbers;
Grid<string>* aBunchOfStrings;
//...etc...
}

//in some function, say `wants` is an enum, and foo is gotten from somewhere:
Foo* foo;
switch wants {
case NUMBERS:
std::cout << "Rows: " << foo->aBunchOfNumbers->GetRows() << std::endl;
std::cout << "Col0 is: " << foo->aBunchOfNumbers->GetTypeofColumn(0) << std::endl;
//...etc...
break;
case STRINGS:
std::cout << "Rows: " << foo->aBunchOfNumbers->GetRows() << std::endl;
std::cout << "Col0 is: " << foo->aBunchOfNumbers->GetTypeofColumn(0) << std::endl;
//...etc...
break;
}

这样做会更容易:

Foo* foo;
Grid* grid;
switch wants {
case NUMBERS:
grid = foo->aBunchOfNumbers;
break;
case STRINGS:
grid = foo->aBunchOfStrings;
break;
}
std::cout << "Rows: " << grid->GetRows() << std::endl;
std::cout << "Col0 is: " << grid->GetTypeofColumn(0) << std::endl;
//...etc...

以同样的方式,如果我使用这样的子类:http://ideone.com/MPKy1w

我知道类模板几乎基本上都是宏以及编译器实际编译它们的方式,但是没有办法通用地引用特化并保存重复吗?

(我在这里故意使用指针,我的实际代码别无选择,我不能在这里复制)

最佳答案

使用所需的方法(“接口(interface)”)创建类。这样做是可能的,因为您的方法不依赖于模板参数 T :

class GridOperations {
virtual int GetRows() = 0;
virtual int getTypeOfColumn(int col) = 0;
virtual ~GridOperations() {}
};

现在从上面的类继承 Grid:

template<T>
class Grid : public GridOperations {
int GetRows() { /* impl */ }
int GetTypeOfColumn(int col) { /* impl */ }
};

现在你可以同时施放 Grid<int>*Grid<string>*GridOperations* :

Foo* foo;
GridOperations* ops;
switch wants {
case NUMBERS:
ops = foo->aBunchOfNumbers;
break;
case STRINGS:
ops = foo->aBunchOfStrings;
break;
}
std::cout << "Rows: " << ops->GetRows() << std::endl;
std::cout << "Col0 is: " << ops->GetTypeofColumn(0) << std::endl;

奖励:你甚至可以使用 std::map<WantEnumType, GridOperations*>以避免讨厌的开关 block 。

关于保存类模板的任何特化的 C++ 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36846101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com