C++ 通过多个函数传递模板参数
C++ Pass template argument through multiple functions
考虑这些代码行。当我尝试编译编译器时,将显示类似'a' is not a member of 'DataType1'
的错误。我了解编译器如何将这些视为错误,但是有什么方法可以避免这种或其他有效的方法吗?
struct DataType1 { public: int x; };
struct DataType2 { public: int a; };
template <class E>
bool job2(E* newData, const int i){
int something = 2;
if (i == 1) newData->x = something;
if (i == 2) newData->a = something;
}
template <class E>
bool job1(List<E>* dataBase){
E* newData = new E;
job2(newData, 1);
dataBase->push_back(newData);
}
template <class E>
int main(){
List<DataType1>* dataBase = new List<DataType>;
job1(dataBase);
}
如果你手头有 C++17,你可以写:
template <class E>
bool job2(E* newData){
int something = 2;
if constexpr (std::is_same_v<E, DataType1>)
newData->x = something;
else
newData->a = something;
}
并完全丢弃i
(如果您仅使用它来区分类型(。
另外,什么反对简单地重载你的函数?
bool job2(DataType1* newData){
commonOperation();
newData->x = something;
}
bool job2(DataType2* newData){
commonOperation();
newData->a = something;
}
其中commonOperation
是函数共有的所有内容。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类