在 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 DMD 2.103 版本泛型函数参数类型判断指南

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

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