C ++ overload function in relation to template type and class hierarchy

Possible duplicate:
Priority when choosing overloaded template functions in C ++

The template function gives me convenience for working with various types:

template<typename T> void destroy(T* obj) { delete obj; } 

But at some point I want to do some specialization in the class hierarchy:

 class Base { virtual void doSomething(); }; class Derived : public Base {}; void destroy(Base* obj) { obj->doSomething(); delete obj; } 

The specified specialized function is called if I pass the exact Base* type, however the overload resolution rules seem to prefer the generic boilerplate version instead of the static act if I pass Derived* to void detroy() .

Of course, I can do all the overloaded functions for all possible derived types, but this is less maintainable.

I am using Visual C ++ 2008, is there any way around the above problem?

+4
source share
2 answers

Other things being equal, overload resolution prefers nontemplate functions for working with templates. However, in this case, all things are not equal. To match your overload for Base* , a database-based pointer mapping is required; no conversion is required to match the function pattern. Thus, the function template is selected for Derived* .

"A simple, albeit probable, error solution would be to make your Derived* to Base* before calling the function.

You could, theoretically, take the SFINAE approach, as Ben suggests, but you would have to explicitly disable the generic function template for any types for which you provide specializations, otherwise you will get perplexed bewilderment. This is even more incomprehensible and error prone than an explicit approach to lithography. (Although, someone here may know another way to get around the ambiguity of the overload, I would be interested to know if this was).

+5
source

There is no such thing as Visual C ++ 2009.

You can specialize your function with another template and use SFINAE only to match Base subtypes. But I don’t know the reasons why the compiler will prefer the second version, usually specialization should be β€œbetter” so that it can be chosen.

Alternatively, you can use the SFINAE class and auxiliary property class to prevent the general version from conforming to Base subclasses. If you need an example of this, ask.

And, of course, your specialization will be used only where it is visible. Template functions are always built-in, they and specializations must be in the header files included by the caller.

0
source

Source: https://habr.com/ru/post/1303377/


All Articles