gpt4 book ai didi

c++ - 有没有办法让函数返回一个类型名?

转载 作者:可可西里 更新时间:2023-11-01 18:19:51 26 4
gpt4 key购买 nike

我最近在做一个项目,想在执行标准以外的操作时优先考虑某些类型。为此,我试图以某种方式使用模板来确定正在使用哪种数据类型。我写的代码显然行不通,但它让我明白了我想做的事情

#include <iostream>

template <type1,type2>
typename determine(type1 a, type2 b)
{
if (typeid(type1) == typeid(int) || typeid(type2) == typeid(int))
return int;
else return double;
}

int main()
{
int a = 3;
double b = 2;
std::cout << (static_cast<determine(a, b)>(a) / static_cast<determine(a, b)>(b)) << std::endl;
}

有没有办法让 determine 返回一些我可以实际用来决定使用什么数据类型的东西?

最佳答案

您可以使用 template metaprogramming实现目标的技巧。

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;

}

关于c++ - 有没有办法让函数返回一个类型名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526400/

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