简体   繁体   中英

C++ : how to use templates to overload return type?

Say I have the following function:

template<typename T> 
shared_ptr<T> my_func(...){
    ....
    .... 
    return make_shared<T>(...);
}

And this function:

template<typename T> 
T my_func(...){
    ....
    ....
    return T(...);
}

Ideally, what I would like to do are things like:

vector<shared_ptr<T>> ptr_vec = { my_func<T>(...), my_func<T>(...), ... };

vector<T> non_ptr_vec = {my_func<T>(...),...};

Without having to "see" more than just the one function name, my_func .


Right now, I have the work-around where I am writing out:

template<typename T>
shared_ptr<T> my_func_shared_ptr(...){...}

template<typename T>
T my_func(...){...}

But this makes for more complexity.

How do I use the templates to accomplish this functionality?

So, thanks to the input in comments, figured out another workaround.

if I introduce a "dummy" class to the template, it becomes sufficient to overload the return type.

template<typename T, typename U>
shared_ptr<T> my_func(...){...}

template<typename T>
T my_func(...){...}

Then,

struct ptr{};

A a = my_func<A>(...);

shared_ptr<A> a_ptr = my_func<A,ptr>(...);

And this becomes a label for the function...compiled and worked. I can also just use this in the inputs, rather than the template:

struct return_ptr{};
struct return_obj{};

template<typename T>
shared_ptr<T> my_func(...,return_ptr return_type){...};

template<typename T>
T my_func(...,return_obj return_type){...};

So that, when calling:

vector<shared_ptr<A>> a_ptrs = {my_func<A>(...,return_ptr()),...};

vector<A> a_objs = {my_func<A>(...,return_obj()),...};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM