52

テンプレート引数の型によって戻り値の型が変わるように関数テンプレートを特化したいと考えています。

class ReturnTypeSpecialization
{
public:
    template<typename T>
    T Item();
};

// Normally just return the template type
template<typename T>
T ReturnTypeSpecialization::Item() { ... }

// When a float is specified, return an int
// This doesn't work:
template<float>
int ReturnTypeSpecialization::Item() { ... }

これは可能ですか?C++11が使えません。

4

5 に答える 5

53

特殊化は戻り値の型の基本テンプレートと一致する必要があるため、「戻り値の型特性」を追加することで一致させることができます。これは、特殊化して真の戻り値の型を引き出すことができる構造体です。

// in the normal case, just the identity
template<class T>
struct item_return{ typedef T type; };

template<class T>
typename item_return<T>::type item();

template<>
struct item_return<float>{ typedef int type; };
template<>
int item<float>();

実例。

以下に固執したい場合があるため、item_return特殊化で戻り値の型を更新するだけでよいことに注意してください。

template<>
item_return<float>::type foo<float>(){ ... }
// note: No `typename` needed, because `float` is not a dependent type
于 2013-04-09T20:49:39.730 に答える
7

ワーカー クラスですべての特殊化を行い、暗黙的に特殊化されるラッパーとして単純な関数を使用します。

#include <iostream>
using std::cout;

// worker class -- return a reference to the given value
template< typename V > struct worker
   {
   typedef V const & type;
   static type get( V const & v ) { return v; }
   };

// worker class specialization -- convert 'unsigned char' to 'int'
template<> struct worker<unsigned char>
   {
   typedef int type;
   static type get( unsigned char const & v ) { return v; }
   };

// mapper function
template< typename V > typename worker<V>::type mapper( V const & v )
   {
   return worker<V>::get(v);
   }

int main()
   {
   char a='A';
   unsigned char b='B';
   cout << "a=" << mapper(a) << ", b=" << mapper(b) << "\n";
   }

この例では、 の特殊化unsigned charにより に変換されるintためcout、文字ではなく数値として表示され、次の出力が生成されます...

a=A, b=66
于 2014-01-23T05:22:45.840 に答える