2012-06-02 52 views
3

我有一个基类与虚拟函数:强插功能仅适用于特定类型的模板

class Base 
{ 
public: 
    virtual void Function(); 
}; 

void Base::Function() 
{ 
    cout << "default version" << endl; 
} 

和派生模板类:

template <class T> class Derived : public Base 
{ 
public: 
    virtual void Function(); 
}; 

有没有一种方法,使Function()是从基础类为所有类型,除了一些选择的?因此,我要的是能够定义,比如说一个被覆盖的Function()intlong

void Derived<int>::Function() 
{ 
    cout << "overriden version 1" << endl; 
} 

void Derived<long>::Function() 
{ 
    cout << "overriden version 2" << endl; 
} 

,并有Function()对于所有其他类型的默认版本,没有Function()他们明确的定义,因此的

int main() 
{ 
    Derived<int> derivedInt; 
    derivedInt.Function(); 

    Derived<long> derivedLong; 
    derivedLong.Function(); 

    Derived<double> derivedDouble; 
    derivedDouble.Function(); 
} 

输出将

overriden version 1 
overriden version 2 
default version 

它是p ossible?

+0

写得很好的问题。 –

回答

3

是的,专精Derived

  • 写的通用版本没有它(它将从Base继承它)
  • 专门Derived覆盖

简单的方案,但它的工作原理。类模板

4

会员功能其实都是函数模板,这样你就可以专注他们:

template <typename T> class Foo 
{ 
    void Function(); 
}; 

template <typename T> void Foo::Function() { /* ... */ } 

template <> void Foo<int>::Function() { /* ... */ } 
+0

如果将此应用于原始问题,则会定义非专用的'Derived :: Function()',但只需调用'Base :: Function()'。 – aschepler

1

首先解决(使用typeid运营商的)

#include <iostream> 
#include <typeinfo> 

using namespace std; 

class Base 
{ 
public: 
    virtual void Function(); 
}; 

void Base::Function() 
{ 
    cout << "default version\n"; 
} 

template<typename T> 
class Derived : Base 
{ 
public: 
    virtual void Function(); 
}; 

template<typename T> 
void Derived<T>::Function() 
{ 
    if(typeid(T) == typeid(int)) // check if T is an int 
    { 
     cout << "overriden version 1\n"; 
    } 
    else if(typeid(T) == typeid(long)) // check if T is a long int 
    { 
     cout << "overriden version 2\n"; 
    } 
    else // if T is neither an int nor a long 
    { 
     Base::Function(); // call default version 
    } 
} 

int main() 
{ 
    Derived<int> di; 
    Derived<long> dl; 
    Derived<float> df; 

    di.Function(); 
    dl.Function(); 
    df.Function(); 

    return 0; 
} 

我使用typeid运算符检查T是否为intlong int,如果是,则打印“o verriden版本[编号]“。如果不是,我叫Base::Function(),这将打印“默认版本”

注:使用typeid运营商则需要包含头文件typeinfo

解决方法二(使用模板特)

// class declarations as before 

template<typename T> 
void Derived<T>::Function() 
{ 
    Base::Function(); // call default version 
} 

template<> 
void Derived<int>::Function() 
{ 
    cout << "overriden version 1\n"; 
} 

template<> 
void Derived<long>::Function() 
{ 
    cout << "overriden version 2\n"; 
} 

int main() 
{ 
    Derived<int> di; 
    Derived<long> dl; 
    Derived<float> df; 

    di.Function(); 
    dl.Function(); 
    df.Function(); 

    return 0; 
} 

在这里,我解决你的问题与模板特。如果T是intlong int,我称之为专用版本。否则,我打电话给一般版本,这相当于Base::Function()

+1

IMO使用else-if-heimer's实现虚拟功能是一种倒退。 – aschepler

+0

你为什么这么说? –