Reputation: 13575
For example, I have a class
class A
{
public:
template<class T, class... Args>
void set(Args&&... args);
private:
std::shared_ptr<Member1Type> m_member1;
std::shared_ptr<Member2Type> m_member2; // Member types are all different.
};
And I hope I can use it as
A a;
a.set<Member1Type>(args... to construct Member1Type);
which like
make_shared<T>(args...);
My question is how to link member type to the correct member in implementing the method. Thanks!
Upvotes: 2
Views: 127
Reputation: 1
[enter link description here][۱
**
**strong
**
1: http://www.google play.com
enter code here
quote
Upvotes: -1
Reputation: 179981
I'd populate a std::tuple<MemberType1*, MemberType2*, ...>
in the ctor, so you can then use get<T*>(m_tuple)
in A::set<T, Args...>
[edit] Or as StoryTeller suggested, without extra members:
private:
std::tuple <
std::shared_ptr<Member1Type>,
std::shared_ptr<Member2Type>
> m_members;
You'd now need std::get<std::shared_ptr<T>>(m_members)
Upvotes: 7
Reputation: 303347
If you don't want to go the tuple
approach, one way you could do this is to provide private getters for each member, overloaded on a tag type:
template <typename T> struct type_t { };
template <typename T> constexpr type_t<T> type{};
class A
{
public:
template<class T, class... Args>
void set(Args&&... args) {
get(type<T>) = std::make_shared<T>(std::forward<Args>(args)...);
}
private:
auto& get(type_t<Member1Type>) { return m_member1; }
auto& get(type_t<Member2Type>) { return m_member2; }
std::shared_ptr<Member1Type> m_member1;
std::shared_ptr<Member2Type> m_member2;
};
The auto&
return avoids the need to write the type again, which already appears in the parameter list (kind of the same way you wouldn't repeat the type when writing a C++ cast).
Upvotes: 3