2016-07-23 84 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>{}); 
    } 
}