【发布时间】:2021-03-04 12:10:21
【问题描述】:
我想做的是让函数根据输入返回不同的类型。 (本质上是返回类型的“重载”)
我对函数进行了模板化,但它不能自动推断类型,我必须手动输入所需的类型。
#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。
-
C++ 中没有返回类型的重载。可以返回一个变体,它本质上是一个类型安全的联合,一次可以包含一个类型。
-
@Peter 我已经足够接近一个有利的结果,问题是调用时我不能只使用 Get();,我必须按顺序使用 Get
()让它工作。我想知道是否可以让模板自动推断类型。 -
@xKaihatsu - 您认为在调用
some_S.Get(some_integral_value)中的信息是编译器推断Get()成员函数的返回类型,特别是如果(在调用点)@987654324 @成员函数已声明但未定义。
标签: c++ function class templates overloading