Force function to accept specific definitions only?

I would like to force a functions parameters to accept only specific definitions. For example, consider #define OUTPUT 1 , #define INPUT 0 and void restrictedFunction(int parameter); .

How would I force restrictedFunction(int parameter) to accept only OUTPUT or INPUT ?

I would also like to take into consideration that another definition may have the same value, for example, #define LEFT 1 and #define RIGHT 0 .

So in this case I would like restrictedFunction(int parameter) to be able to accept only OUTPUT and INPUT specifically.


typedef enum { INPUT = 0, OUTPUT = 1 } IO_Type;

void restrictedFunction(IO_Type parameter) { ... }

It doesn't absolutely force the use of the values (the compiler will let someone write restrictedFunction(4) ), but it is about as good as you'll get.

If you truly want to force the correct type, then:

typedef enum { INPUT = 0, OUTPUT = 1 } IO_Type;
typedef struct { IO_Type io_type } IO_Param;

void restrictedFunction(IO_Param parameter) { ... }

In C99 or later, you could call that with:

restrictedFunction((IO_Param){ INPUT });

This is a compound literal, creating a structure on the fly. It is not entirely clear that the structure type really buys you very much, but it will force the users to think a little and may improve the diagnostics from the compiler when they use it wrong (but they can probably use restrictedFunction((IO_Param){ 4 }); still).

What this means is that your restrictedFunction() code should be ready to validate the argument:

void restrictedFunction(IO_Type io_type)
{
    switch (io_type)
    {
    case INPUT:
        ...do input handling...
        break;
    case OUTPUT:
        ...do output handling...
        break;
    default:
        assert(io_type != INPUT && io_type != OUTPUT);
        ...or other error handling...
        break;
    }
}

You could use an enum.

typedef enum TrafficDirection { INPUT = 0, OUTPUT = 1 } TrafficDirection;

restrictedFunction(TrafficDirection direction);

of course, this isn't perfect. You can still pass any int to it as long as you use a cast.

restrictedFunction((TrafficDirection) 4);

你没有得到尽可能多的保护,但你可以这样做:

enum func_type { INPUT, OUTPUT };
void restrictedFunction( enum func_type parameter );
链接地址: http://www.djcxy.com/p/73568.html

上一篇: 在linux kernel.h文件中定义的宏

下一篇: 强制函数只接受特定的定义?