c++ - 根据派生类型选择类的显式特化

标签 c++ templates explicit-specialization

您好,我在选择具有显式特化的模板类的正确版本时遇到了问题。我想使用用于特化的类的派生类来选择特化。场景是:

#include <stdio.h>

class A
{};

class B: public A
{};

template<typename T>
class Foo
{
public:
   int FooBar(void) { return 10; }
};

// Explicit specialization for A
template<> int Foo< A >::FooBar( void ) { return 20; }

void main( void)
{
   Foo<B> fooB;

   // This prints out 10 instead of wanted 20 ie compiler selects the general version
   printf("%d", fooB.FooBar() );
}

正如我在评论中所说,我希望看到 20 被打印出来,因为 B 是从 A 派生出来的,但是 10 被打印出来了。如何在不为每个派生类编写专门化的情况下获取专门化(我的实际场景有很多派生类型)。

最佳答案

---编辑:新答案让我们使原始方法更易于维护。 所有重要的选择都可以在 Foo 的定义中找到。它应该易于维护。

#include <boost/mpl/if.hpp>
#include  <boost/type_traits/is_base_of.hpp>
#include <iostream>

class A
{};

class B: public A
{};

class C{};
class D : public C{};
class E{};

struct DefaultMethod
{
    static int fooBar() { return 10; }
};
struct Method1
{
    static int fooBar() { return 20; }
};
struct Method2
{
    static int fooBar() { return 30; }
};

template<typename T, typename BaseClass, typename Choice1, typename OtherChoice>
struct IfDerivesFrom :
    boost::mpl::if_<
        typename boost::is_base_of<BaseClass, T>::type,
        Choice1,
        OtherChoice>::type
{
};

template<typename T>
struct Foo :
    IfDerivesFrom<T, A,
      Method1,
      IfDerivesFrom<T, C,
          Method2,
          DefaultMethod>
      >
{
};

int main()
{
    std::cout << Foo<A>::fooBar() << std::endl;
    std::cout << Foo<B>::fooBar() << std::endl;
    std::cout << Foo<C>::fooBar() << std::endl;
    std::cout << Foo<D>::fooBar() << std::endl;
    std::cout << Foo<E>::fooBar() << std::endl;

    return 0;
}

---原始答案 如果可以使用 boost,则可以执行以下操作:

#include  <boost/type_traits/is_base_of.hpp>

template<bool b>
class FooHelper
{
    int FooBar();
};
template<> FooHelper<true>::FooBar(){ return 20;}
template<> FooHelper<false>::FooBar(){ return 10;}

template<typename T>
class Foo
{
public:
   int FooBar(void) { return FooHelper<boost::is_base_of<A, T>::type::value>(); }
};

关于c++ - 根据派生类型选择类的显式特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2118782/

相关文章:

c++ - Visual Studio 中的正则表达式

C++ 纯虚错误

c# - 实现接口(interface)正确的术语

c++ - swig : undefined symbol: _ZN7hosters11hostersLink7getLinkEi 错误

c++ - 显式特化不能是友元声明

c++ - 具有静态方法的模板专用类是否占用存储空间?

C++ 函数模板特化和重载

c++ - 如何引用作为模板参数传递的派生类中定义的类型?

c++ - 在 C++ 模板中禁用代码的示例

c++ - 如何根据类参数定义成员类运算符