gpt4 book ai didi

c++ - 模板成员函数无法自动推断类型

转载 作者:行者123 更新时间:2023-12-03 07:09:13 26 4
gpt4 key购买 nike

我想要做的是让函数根据输入返回不同的类型。 (本质上是返回类型的“重载”)
我对函数进行了模板化,但它不能自动推断类型,我必须手动输入所需的类型。

#include <iostream>

using namespace std;

struct S {

template<typename T>
T Get(int type) {
if (type == 0) {
return 4;
} else if (type == 1) {
return true;
} else {
return -1;
}
};

};

int main() {
cout << boolalpha;

S s;

// ok
int x = s.Get<int>(0); // return an integer
bool y = s.Get<bool>(1); // return a boolean

// ERROR
// the end goal is something like this
// is there a better way to handle this?
int a = s.Get(0);
bool b = s.Get(1);

cout << "x: " << x << '\n'; // “x: 4”
cout << "y: " << y << '\n'; // “y: true”

}

最佳答案

如果你有 C++17,那么你可以使用 if-constexpr像这样:

struct S {

template<int type>
auto Get() {
if constexpr (type == 0) {
return 4;
}
else if constexpr (type == 1) {
return true;
}
else {
return -1;
}
};

};
现在取决于 type 的值正确的 if-constexpr分支将被编译并返回适当的类型。
您可以像这样使用上面的代码:
S s;

int x = s.Get<0>(); // return an integer
bool y = s.Get<1>(); // return a boolean
这是 demo .
请注意 type值必须在编译时知道。在 C++ 中,你不能有一个函数在运行时返回不同类型的值。您必须使用 std::variantstd::any要做到这一点。

关于c++ - 模板成员函数无法自动推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64940277/

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