2012-12-27 13 views
2

我有一個函數模板:專業化面向相同的模板參數

//the most generalized template 
template<typename typeArg, typename typeRet> 
typeRet func(const typeArg &val); 

和若干專業化它,它看起來像:

template<> 
someType func(const otherType &val) 
{ 
    //code 
} 

template<> 
typeFoo func(const typeBar &val) 
{ 
    //more code 
} 

但它沒有缺省實現。

顯然,這兩種類型不能自動推導,所以通話的樣子:

type1 var1 = func<argType,type1>(arg); 

什麼是寫僅當類型相同的情況下的默認實現的正確方法?

我嘗試了一些變種:

1日嘗試

template<typename theOnlyType, theOnlyType> 
theOnlyType func(const typeArg &theOnlyType) 
{ 
    //code 
} 

但這是錯誤的,因爲這個功能只有一個模板參數,它不符合上面的電話。

第2次嘗試

template<typename type1, typename type2> 
type1 func(const type1 &theOnlyType) 
{ 
    //code 
} 

通話變得模糊,考生此功能,並從第一個代碼塊的最廣義的模板。

+0

你的意思是你想要一個默認的實現,其中'typeArg'與'typeRet'相同 – 0x499602D2

+0

部分專業化會在這裏工作嗎? – ulidtko

+0

是的,我的意思是類型相同時的默認實現。 不,部分專業化功能是不允許的。 – Sergey

回答

3

經過一番研究後,我想出了一個更好的解決方案。它包括在靜態方法中添加一個包裝類,並通過全局方法調度它們:

#include <iostream> 

namespace tag 
{ 
    template <typename U, typename P> 
    struct wrapper // default implementation 
    { 
     static U foo(P const &) 
     { 
      std::cout << "different types"; 
      return U(); 
     } 
    }; 
} 

namespace tag 
{ 
    template <typename T> 
    struct wrapper<T, T> // specialized 
    { 
     static T foo(T const &) 
     { 
      std::cout << "same type"; 
      return T(); 
     } 
    }; 
} 

template <typename U, typename P> 
static inline U foo(P const &p) 
{ 
    return tag::wrapper<U, P>::foo(p); 
} 

int main() 
{ 
    foo<int>(0); 
    foo<int>(true); 
} 

我希望這有助於。


使用 std::enable_ifstd::is_same(C++ 11):

template <typename A, typename B, typename = 
      typename std::enable_if<std::is_same<A, B>::value>::type> 
B foo(const A &) { 

} 

或使用該版本的C++ 03和更早的版本:

template <typename A, typename B> struct foo; // implement for different types 

template <typename T> struct foo<T, T> { 
    T operator()(const T &) { 
     // default impelentation 
    } 
}; 

int main() { 

    foo<int, int> f; 
    int n; 

    f(n); 

} 

我敢肯定有一種改善這種情況的方法。我試圖使用該功能的部分專業化,但我無法讓它爲我工作。

+0

這個結構在C++ 03中可用嗎?我不能使用新標準。 – Sergey

+0

你沒有說C++ 11。但是我有另一個使用'struct's的例子。這會有幫助嗎? – 0x499602D2

+0

大概就是這樣,請把它展示出來。 – Sergey