受此答案的启发,我尝试复制并粘贴(并添加测试main())此代码:
template<typename T>
std::tuple<int, double> foo(T a) {
if constexpr (std::is_same_v<int, T>)
return {a, 0.0};
else if (std::is_same_v<double, T>)
return {0, a};
else
return {0, 0.0};
}
int main() {
auto [x, y] = foo("");
std::cout << x << " " << y;
}
Run Code Online (Sandbox Code Playgroud)
这非常简单 - 如果T推断为int,我们想要返回一个元组[a, 0.0].如果T推断为double,我们想要返回一个元组 [0, a].否则,我们想要回来[0, 0.0].
正如你所看到的,在main()函数中,我foo用const char*参数调用,这应该导致x和 …