有没有办法让函数返回一个类型名? [英] Is there a way to make a function return a typename?

查看:35
本文介绍了有没有办法让函数返回一个类型名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was working on a project recently and wanted to give precedence to certain types when performing operations other than what is standard. To do this I was attempting to use a template somehow to determine what kind of datatypes were being used. The code I have written clearly doesn't work, but it gets the idea of what I'm trying to do across

#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;
}

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

Is there a way to make determine return something that I can actually use to decide what datatype to use?

推荐答案

您可以使用 模板元编程 实现目标的技巧.

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;

}

这篇关于有没有办法让函数返回一个类型名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆