2011-02-07 78 views
3

我目前正在重构一些代码,明确地专门化了具有两个模板参数的类模板的成员函数。部分专门化的成员函数实现

template <class S, class T> 
class Foo 
{ 
    void bar(); 
}; 

template <class S, class T> 
void Foo<S, T>::bar() 
{ /* Generic stuff */ } 

template <> 
void Foo<SomeType, SomeType>::bar() 
{ /* Some special function */ } 

现在我增加了一些更多的模板参数,因此该类现在看起来是这样的:

template <class S, class EXTRA0, class T, class EXTRA1> 
class Foo 
{ 
    void bar(); 
}; 

这两个额外的参数只需添加类型定义上我的课,所以运行时功能不真的改变了。有什么办法可以保持酒吧的(现在部分)专门的实施?我似乎无法弄清楚它的语法,我有一种预感可能是不可能的。

编辑:我在寻找类似:

template <class EXTRA0, class EXTRA1> 
void foo<SomeType, EXTRA0, Sometype, EXTRA1>::bar() 
{ 
    /* specialized implementation */ 
} 

这似乎并没有编译..

+1

据我所知,你还记得正确的:你不能部分专门功能,只有类型。 – Simone 2011-02-07 10:17:54

+0

@Simone它的工作,至少在g ++。 – UmmaGumma 2011-02-07 10:22:05

回答

3

你是正确的,这是不可能的。

您可以做的是在新的Foo中创建一个帮助成员类模板,并将其作为非模板成员函数放入其中。专门帮助类而不是函数。

另一种选择是将专业化转变为非模板过载。

1

我不认为你想要的是那样容易。

template <class S, class EXTRA0, class T, class EXTRA1> 
class FooBase 
{ 
    void bar(); 
}; 

template <class S, class EXTRA0, class T, class EXTRA1> 
void FooBase<S, EXTRA0, T, EXTRA1>::bar() 
{ /* Generic stuff */ } 

template <class S, class EXTRA0, class T, class EXTRA1> 
class Foo 
    : public FooBase <S, EXTRA0, T, EXTRA1> 
{ }; 

template <class EXTRA0, class EXTRA1> 
class Foo<int, EXTRA0, int, EXTRA1> 
    : public FooBase <int, EXTRA0, int, EXTRA1> 
{ 
    void bar(); 
}; 

template <class EXTRA0, class EXTRA1> 
void Foo<int, EXTRA0, int, EXTRA1>::bar() 
{ /* Some special function */ } 
1

可以使基类,在这里你可以定义你的所有成员,除了酒吧(),然后创建派生类(一个用于一般用途,一为SOMETYPE):

template <class S, class T> 
class FooBase 
{ 
     // All other members 
}; 

template <class S, class EXTRA0, class T, class EXTRA1> 
class Foo:public FooBase<S,T> 
{ 
public: 
     void bar() 
     { 

     } 
}; 

struct SomeType {}; 

template <class EXTRA0, class EXTRA1> 
class Foo<SomeType,EXTRA0,SomeType,EXTRA1>:public FooBase<SomeType,SomeType> 
{ 
public: 
    void bar() 
    { 

    } 
}; 

int main() 
{ 
    Foo<SomeType,int,SomeType,int> b; 
    b.bar(); 
} 
关于这样的事情是什么
1

您可以通过使用一个专攻仿函数,而不是一个功能做到这一点:

#include <iostream> 

typedef int SomeType; 

template <class A, class B> 
class BarFunctor { 
public: 
    void operator()() { 
     std::cout << "generic" << std::endl; 
    } 
}; 

template <> 
class BarFunctor<SomeType, SomeType> { 
public: 
    void operator()() { 
     std::cout << "special" << std::endl; 
    } 
}; 

template <class S, class T, class EXTRA0, class EXTRA1> 
class Foo { 
public: 
    void helloWorld() { 
     std::cout << "hello world !" << std::endl; 
    } 

    void bar() { 
     return _bar(); 
    } 

private: 
    BarFunctor<S, T> _bar; 
}; 

int main() { 

    Foo<char, char, char, char> gen; 
    Foo<SomeType, SomeType, char, char> spe; 
    gen.helloWorld(); 
    spe.helloWorld(); 
    gen.bar(); 
    spe.bar(); 
    return 0; 
}