访问模板对象的成员函数时发生编译错误



我刚开始学习面向对象编程。我正在尝试访问一个模板函数中两个不同类的成员函数。我限制了对基于布尔标志isAggregateElement的成员函数的访问。由于某种原因,编译器抛出错误,指出并没有这样的成员函数。

class descriptor{
public:
int getName(){
return -5;
}
};
class aggregate{
public:
int getDescription() {
return 234;
}
int getUnit(){
return 1;
}
};
template <typename T>
void buildObjectInfo(const T& classMemberType, const bool& isDataInterface){

T baseTypeElement = classMemberType;
bool isAggregateElement = !isDataInterface;

if(isAggregateElement){
cout<<baseTypeElement.getUnit()<<endl;
} else {
cout<<baseTypeElement.getName()<<endl; // Error gets resolved if I remove the else construct
}
}
int main()
{
aggregate a;
descriptor d;
buildObjectInfo<aggregate>(a,false);
return 0;
}

在不删除布尔条件(或(删除模板函数中的else构造的情况下,我应该如何访问getUnit((?

两个分支都必须有效。假设您调用buildObjectInfo(d,false),那么会发生什么?

可以使用constexpr if来丢弃false分支。

请注意,getter应该是const方法。模板参数可以从函数参数中推导出来,不需要bool:

#include <iostream>
#include <type_traits>
struct descriptor{
int getName() const { return -5; }
};
struct aggregate{
int getDescription() const { return 234; }
int getUnit() const { return 1; }
};
template <typename T>
void buildObjectInfo(const T& t){
if constexpr(std::is_same_v<aggregate,T>) {
std::cout << t.getUnit() << 'n';
} else {
std::cout << t.getName() << 'n';
}
}
int main() {
aggregate a;
descriptor d;
buildObjectInfo(a);
buildObjectInfo(d);
}

然而,对于两种不同的类型,重载函数要简单得多:

#include <iostream>
struct descriptor{
int getName() const { return -5; }
};
struct aggregate{
int getDescription() const { return 234; }
int getUnit() const { return 1; }
};
void buildObjectInfo(const aggregate& t) {
std::cout << t.getUnit() << 'n';
}
void buildObjectInfo(const descriptor& t) {
std::cout << t.getName() << 'n';
}
int main() {
aggregate a;
descriptor d;
buildObjectInfo(a);
buildObjectInfo(d);
}

最新更新