2016-07-23 63 views
4

假设我有一个符合 简化到这个动态指定要使用基于模板类型的方法

template<typename t,typename u> 
std::shared_ptr<bar> MyClass::getFunct(std::string SomeStr) 
{ 
    ..... 
    std::map<std::string,std::shared_ptr<foo> > j; 
    .... 
    std::shared_ptr<u> collection(new u()); 
    for (auto val : j){ 
    val.second->getMethodA() //Will return object of type t <----LINE A 
    } 
} 

现在的方法,我用它作为

getFunct<FirstType>("SomeString") 
getFunct<SecondType>("SomeString") 
getFunct<ThirdType>("SomeString") 

现在val.second有3种方法

val.second->getMethodA() //returns a type of FirstType 
val.second->getMethodB() //returns a type of SecondType 
val.second->getMethodC() //returns a type of ThirdType 

当前我使用的是 val.second->getMethodA()与模板类型FirstType

有反正对我来说,指定要使用getMethodB如果模板类型是SecondType 和使用getMethodC如果模板类型为ThirdType

+1

这听起来像XY的问题。你试图解决什么设计问题?绑定功能对象是可能的通过'std :: bind()' – lorro

+0

让我修复那个抱歉 –

回答

1

最简单的办法是更换三个getMethodX成员函数单个模板函数template<class T> T foo::getMethod()。然后根据需要为每种类型创建专业化。

但如果是不适合的设计,那么你可以使用一个包装函数:

template<class T> 
struct helper {}; 

template<> 
struct helper<FirstType> { 
    static FirstType getMethod(foo& f) { 
     return f.getMethodA(); 
    } 
}; 
// repeat specializations for other member functions 
+0

是啊,看起来我将不得不实施这样的事情 –

1

用C++ 17可以使用constexpr if

template<typename T> 
decltype(auto) foo(Bar& bar){ 
    if constexpr(std::is_same_v<T,FirstType>){ 
     return bar.getMethodA(); 
    } 
    if constexpr(std::is_same_v<T,SecondType>){ 
     return bar.getMethodB(); 
    } 
    if constexpr(std::is_same_v<T,ThirdType>){ 
     return bar.getMethodC(); 
    } 
} 
1

在没有我可能会去这样简单的事情:

template <typename T> struct type {}; 

struct select 
{ 
    bar &b; 
    decltype(auto) operator()(type<FirstType>) const { return b.getMethodA(); } 
    decltype(auto) operator()(type<SecondType>) const { return b.getMethodB(); } 
    decltype(auto) operator()(type<ThirdType>) const { return b.getMethodC(); } 
}; 
select{*val.second}(type<T>{}); 

在上下文中你的例子:

template <typename T> struct type {}; 

template<typename t,typename u> 
std::shared_ptr<bar> MyClass::getFunct(std::string SomeStr) 
{ 
    ..... 
    std::map<std::string,std::shared_ptr<foo> > j; 
    .... 
    for (auto val : j) { 
     struct select { 
      bar &b; 
      decltype(auto) operator()(type<FirstType>) const { return b.getMethodA(); } 
      decltype(auto) operator()(type<SecondType>) const { return b.getMethodB(); } 
      decltype(auto) operator()(type<ThirdType>) const { return b.getMethodC(); } 
     }; 
     select{*val.second}(type<t>{}); 
    } 
}