Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Determine template type from the constructor argument.

27 views
Skip to first unread message

Glen Stark

unread,
May 27, 2015, 8:55:34 AM5/27/15
to
Hi everyone

I have something like the following:

template <typename T>
class Foo
{
Foo(std::vector<T*>);
/*...*/
}

Now I'd like to be able to instantiate Foo without specifying the type,
since I already have the type available to the constructor... For
example, if I were so inclined, I could write the following:

std::vector<some_component_type> components;
Foo<std::remove_pointer<decltype(components)::value_type>::type>
cm(components);

and it would compile.

I'm doing a refactoring where this obviously that's a silly way of doing
this. I'd like to be able to do
Foo f(components);

and have the correct type instantiated. Is that possible? Is it
considered evil since it's no longer obvious it's a different type than
Foo g (diff_components)

What wisdom do you have to offer?

Wouter van Ooijen

unread,
May 27, 2015, 9:02:19 AM5/27/15
to
Glen Stark schreef op 27-May-15 om 2:55 PM:
> Hi everyone
>
> I have something like the following:
>
> template <typename T>
> class Foo
> {
> Foo(std::vector<T*>);
> /*...*/
> }
>
> Now I'd like to be able to instantiate Foo without specifying the type,
> since I already have the type available to the constructor... For
> example, if I were so inclined, I could write the following:
>
> std::vector<some_component_type> components;
> Foo<std::remove_pointer<decltype(components)::value_type>::type>
> cm(components);
>
> and it would compile.
>
> I'm doing a refactoring where this obviously that's a silly way of doing
> this. I'd like to be able to do
> Foo f(components);

It seems that you (IMO rightly) object to mentioning T both explictily
in the type and implicitly in the parameter. Maybe a good alternative is:

auto f = Foo( components );

?


Wouter van Ooijen

Victor Bazarov

unread,
May 27, 2015, 9:36:30 AM5/27/15
to
The usual solution to it is to roll your own "make_a_Foo" function:

template<class T> Foo<T> make_a_Foo(T t) { return
Foo<T>(t);
}

after that, do the 'auto' trick:

auto f = make_a_Foo(components);

V
--
I do not respond to top-posted replies, please don't ask

Wouter van Ooijen

unread,
May 27, 2015, 9:49:58 AM5/27/15
to
Victor Bazarov schreef op 27-May-15 om 3:36 PM:
What are the advantages of using such a function over the direct use of
the constructors?

Wouter

Victor Bazarov

unread,
May 27, 2015, 10:05:53 AM5/27/15
to
"Direct use of the constructors" requires specifying the type in the
angle brackets after the template name. Using such a function removes
that necessity. Did you try experimenting with your suggestion? Could
you post the code that works that uses only the c-tor, please?
0 new messages