4

Considering a template function like below how is it possible to do explicitly specialize one version of function for multiple types:

template <typename T>
void doSomething(){
 //whatever
}

The intention is to have one specialization instead of multiple following ones because //something is the same:

void doSomething<int>(){
 //something
}
void doSomething<float>(){
 //something
}
void doSomething<double>(){
 //something
}

any method to achieve one specialization?

4

3 に答える 3

4

テンプレート機能の特化はできません。ただし、関数から使用できるヘルパー クラスで実装を委任することもできます。いくつかのスケルトン コード:

テンプレート クラスを実装し、特殊化します。

template< typename T, bool isArithmetic>
struct Something { void operator()() { ... } };

template< typename T, true>
struct Something { void operator()() { ... do something specialized for arithmetic types; } }

次に、テンプレート関数で使用します。

template< typename T>
void myFunction()
{
   Something<T, IsArithmetic<T>::value>()();
}

IsArithmetic は、型 T (セレクター) に関する情報を提供するクラスです。このような型情報は、たとえばブースト ライブラリで見つけることができます。

于 2010-11-25T18:55:39.380 に答える
1

一種の doSomethingImpl 関数を持つことができます。

template<typename T> doSomethingImpl() {
    // whatever
}
template<typename T> doSomething() {
    // something else
}
template<> doSomething<float>() {
    doSomethingImpl<float>();
}
template<> doSomething<int>() {
    doSomethingImpl<int>();
}

SFINAE や などを使用して、より一般的に特化することもできstd::is_numeric<T>ます。

于 2010-11-25T18:52:15.253 に答える