开发者

Accepting data-type of input dynamically

Hii ,

I was writing a generic function for sorting when i came across this idea . Usually we give the data and call the function sort which is written in a generic manner. I was wondering if we could accept the data-type of the input dynamically at run-time using generics .

Like开发者_如何学运维 , if we want to sort some data and we do not know the type of input that is given before hand . So , we need to take the data-type of input dynamically and perform the sort .

Is it possible .. ???


Yeah, if only somebody had though of that before...

Sort algorithms in libraries are generally pretty generic. You just need to tell them how to compare your objects.


I was wondering if we could accept the data-type of the input dynamically at run-time using generics...

....we want to sort some data and we do not know the type of input that is given before hand...

No, you can't do that with C++ templates (I assumed you meant templates when you said generics).

C++ templates are a language feature that allows for types in code to be unspecified until the code that uses them is compiled. That is, C++ templates are a compile-time feature.

If all the types involved are known by the time the code is compiled, then you can use C++ templates. In your sorting example, if you know the exact types of the data to be sorted, then something like the std::sort() function can be used.

If you can't determine the exact types of objects until runtime (which is apparently the situation you're describing), then polymorphism via virtual functions should be used. Using your sorting example, you may have a base class like this:

class SortableInput
{
public:
    virtual bool IsLessThan(SortableInput& rhs) = 0;
};

Then your different types can derive from it:

class SortableItemA : public SortableInput
{
public:
    virtual bool IsLessThan(SortableInput& rhs) { /* */ }
};

class SortableItemB : public SortableInput
{
public:
    virtual bool IsLessThan(SortableInput& rhs) { /* */ }
};

// ...

Then your sort function would only have to know about SortableInput. Of course, this only really makes sense if a SortableItemA can actually be compared against a SortableItemB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜