gpt4 book ai didi

c++ - 模板化类的特殊继承导致成员函数返回模板化类类型而不是继承类类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:05 25 4
gpt4 key购买 nike

假设我有一个这样的基类:

template<typename T>
class Base {
public:
Base& operator()(const T& value) {
this->value = value;
return *this;
}
T value;
};

现在我想继承这个类来创建特定于类型的类

class InheritedFloat : public Base<float> {} inheritedFloat;

现在我尝试在一个函数中捕捉这个继承:

void function(const InheritedFloat& inherited) {
std::cout << inherited.value << '\n';
}

像这样调用这个函数当然没问题:

int main() {
function(inheritedFloat); //(inheritedFloat is a global instance)

return 0;
}

但是当我尝试用 operator()(const float& value){...} 调用它时成员函数,function(const InheritedFloat& inherited){...}不认为它是 InheritedFloat -Type 而不是 Base<float> -类型:

int main() {
function(inheritedFloat(10.f)); //error

return 0;
}

错误:

Error   C2664   'void function(const InheritedFloat &)': cannot convert argument 1 from 'Base<float>' to 'const InheritedFloat &'

那么我怎样才能使operator()(const T& value){...}返回 InheritedFloat&而不是 Base<float>&


为了进一步说明,这只是一个简化的示例(当然)。我有几十个继承案例。所以我不能只是模板指定 function()

template<typename T>
void function(const Base<T>& inherited) {
std::cout << inherited.value << '\n';
}

因为每一种继承都需要区别对待。类型会重叠,所以会有多个 Base<std::size_t > 案例,例如。

完整代码:

#include <iostream>

template<typename T>
class Base {
public:
Base& operator()(const T& value) {
this->value = value;
return *this;
}
T value;
};

class InheritedFloat : public Base<float> {} inheritedFloat;


void function(const InheritedFloat& inherited) {
std::cout << inherited.value << '\n';
}

int main() {
function(inheritedFloat(10.f));

return 0;
}

感谢阅读,感谢您的帮助!

最佳答案

您可以利用 CRTP这里。通过提供额外的模板参数,您可以使基类函数返回对派生类的引用:

#include <iostream>

template<typename Derived, typename T>
class Base {
public:
Derived & operator()(const T& value) {
this->value = value;
return *static_cast<Derived *>(this);
}
T value;
};

class InheritedFloat : public Base<InheritedFloat, float> {} inheritedFloat;


void function(const InheritedFloat& inherited) {
std::cout << inherited.value << '\n';
}

int main() {
function(inheritedFloat(10.f));

return 0;
}

online compiler

关于c++ - 模板化类的特殊继承导致成员函数返回模板化类类型而不是继承类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771426/

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