次のような API を使用しようとしています。
#include<iostream>
#include<boost/optional.hpp>
class Base
{
int id;
public:
int get_id()
{
return id;
}
};
class A : public Base
{
};
class B : public Base
{
};
class M
{
public:
enum Type
{
t_A,
t_B
};
Type type;
boost::optional<A&> a;
boost::optional<B&> b;
boost::optional<A&> get_A()
{
return a;
}
boost::optional<B&> get_B()
{
return b;
}
};
派生クラスを介してベースに到達する必要があります。そこで、次のようなテンプレート化された関数を作成しました。
template<class T>
boost::optional<T&> get(M & m)
{
switch(m.type)
{
case M::t_A :
return m.get_A();
case M::t_B :
return m.get_B();
default:
throw;
};
}
int main()
{
M m;
//... initialization of m
int i = get<>(m)->get_id();
return 0;
}
しかし、私の関数のテンプレート引数は推測できません:
template_sp_1.cpp:63:17: error: no matching function for call to ‘get(M&)’
int i = get<>(m)->get_id();
^
template_sp_1.cpp:63:17: note: candidate is:
template_sp_1.cpp:46:21: note: template<class T> boost::optional<T&> get(M&)
boost::optional<T&> get(M & m)
^
template_sp_1.cpp:46:21: note: template argument deduction/substitution failed:
template_sp_1.cpp:63:17: note: couldn't deduce template parameter ‘T’
int i = get<>(m)->get_id();
次のいずれかを試すことはできません。どうやらboost::optional
:
int i = get<Base>(m)->get_id();
int i = get<A>(m)->get_id();
int i = get<B>(m)->get_id();
そのようなシナリオに対する解決策はありますか? (APIには触れられません)