在D语言中,可以使用模板来实现泛型函数。在模板中,可以使用is关键字来判断参数的类型。

以下是几个完整可以运行的具体例子:

  1. 判断参数是否为整数类型:
import std.stdio;

template isInteger(T)
{
    static const bool value = is(T == int) || is(T == long) || is(T == short) || is(T == byte) || is(T == ubyte) || is(T == uint) || is(T == ulong) || is(T == ushort);
}

void foo(T)(T arg)
{
    if (isInteger!T)
    {
        writeln("arg is an integer");
    }
    else
    {
        writeln("arg is not an integer");
    }
}

void main()
{
    foo(42);
    foo(3.14);
}

输出:

arg is an integer
arg is not an integer
  1. 判断参数是否为可迭代对象:
import std.stdio;
import std.algorithm;

template isIterable(T)
{
    static const bool value = is(typeof(iterationScheme!T));
}

void foo(T)(T arg)
{
    if (isIterable!T)
    {
        writeln("arg is iterable");
        foreach (e; arg)
        {
            writeln(e);
        }
    }
    else
    {
        writeln("arg is not iterable");
    }
}

void main()
{
    int[] arr = [1, 2, 3];
    foo(arr);
    foo(42);
}

输出:

arg is iterable
1
2
3
arg is not iterable
  1. 判断参数是否为字符串类型:
import std.stdio;

template isString(T)
{
    static const bool value = is(T == string) || is(T == immutable(char)[]);
}

void foo(T)(T arg)
{
    if (isString!T)
    {
        writeln("arg is a string");
    }
    else
    {
        writeln("arg is not a string");
    }
}

void main()
{
    foo("hello");
    foo('c');
}

输出:

arg is a string
arg is not a string
``
dlang语言最新dmd2103版本编写泛型函数时候怎么判断参数的类型给我几个完整可以运行的具体例子

原文地址: https://www.cveoy.top/t/topic/fbjq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录