c++ - 多种类型的模板方法特化

标签 c++ templates c++11

我有一个公开模板方法 foo 的类“A”。 Foo 有一个标准实现,可以很好地与 B、C 配合使用。它还有一个针对 D 的特殊实现。

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D>
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
}

现在,我需要添加类 E,它要求“foo”具有与 D 相同的特殊实现。 有没有办法这样说:对于所有类型,使用标准的 foo.对于D,E(等等)的特殊实现。

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D && E>  <-- PseudoCode - It doesn't work
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};
class E{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
  A<E> a4;
}

我正在考虑使用特征类。但我希望有更简单的方法来实现这一目标。 谢谢

最佳答案

使用 Walter Brown 的 (C++1z) void_t .

#include <iostream>
#include <type_traits>

template <typename...>
using void_t = void;

template <typename T, typename = void>
struct has_bar 
  : std::false_type { };

template <typename T>
struct has_bar<T, void_t<decltype( std::declval<T&>().bar() ) > >
  : std::true_type { };

class A {
  public:
    void foo() { };
};

class B {
  public:
    void bar() { };
};

class C {
  public:
    void bar() { };
};

template <typename T> 
typename std::enable_if<!has_bar<T>::value, void>::type
fun(T t) {
  std::cout << "fun" << std::endl;
}

template <typename T>
typename std::enable_if<has_bar<T>::value, void>::type
fun(T t) {
  std::cout << "special fun" << std::endl;
}

代码...

int main(const int argc, const char* argv[argc]) {

  A a;
  B b;
  C c;

  fun(a);
  fun(b);
  fun(c);

  return 0;
}

打印出来

fun
special fun
special fun

请注意,它不检查任何类型语义,因此最好将 bar() 声明为接口(interface)并使用 std::is_base_of 可能更好.

关于c++ - 多种类型的模板方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421807/

相关文章:

c# - 使用 CreateProcessAsUser 启动 url

c++ - 成员函数调用和C++对象模型

c++ - 我可以对宏使用哪些技巧?

c++ - 使用模板递归检查函数方法是否存在

c++ - 如何实现内部实现依赖于模板参数的类?

c++ - 如何在 Windows 上将 C++11 线程关联设置为 NUMA 节点?

C++ - 为什么 boost::hash_combine 是组合散列值的最佳方式?

c++ - 用双花括号初始化 vector :std::string vs int

c++ - LNK2019带模板

c++ - std::shared_ptr 异常安全