更新时间:2021-10-26 01:40:41
您可以使用 模板元编程 实现目标的技巧.
You can use template metaprogramming techniques to accomplish your goal.
template <typename T1, typename T2> struct TypeSelector
{
using type = double;
};
template <typename T1> struct TypeSelector<T1, int>
{
using type = int;
};
template <typename T2> struct TypeSelector<int, T2>
{
using type = int;
};
template <> struct TypeSelector<int, int>
{
using type = int;
};
然后,使用:
int main()
{
int a = 3, b = 2;
using type1 = TypeSelector<decltype(a), decltype(b)>::type;
std::cout << (static_cast<type1>(a) / static_cast<type1>(b)) << std::endl;
float c = 4.5f;
using type2 = TypeSelector<decltype(a), decltype(c)>::type;
std::cout << (static_cast<type2>(a) / static_cast<type2>(c)) << std::endl;
using type3 = TypeSelector<decltype(c), decltype(a)>::type;
std::cout << (static_cast<type3>(c) / static_cast<type3>(a)) << std::endl;
}