c++ - 模板:只有在类有方法时才执行

标签 c++ templates template-function

我想编写一个函数来执行某个模板类的方法,但如果该类没有它,也应该可以正常编译。在那种情况下,它不应该调用该函数。

struct A
{
   void func() {}
};

struct B
{
};

template <typename T>
void anotherFunc(T t)
{
   //do t.func() here if T implements func, just do nothing if it doesn't.
}

这有可能吗?

最佳答案

// type_sink takes a type, and discards it.  type_sink_t is a C++1y style using alias for it
template<typename T> struct type_sink { typedef void type; };
template<typename T> using type_sink_t = typename type_sink<T>::type;

// has_func is a traits class that inherits from `true_type` iff the expression t.func()
// is a valid one.  `std::true_type` has `::value=true`, and is a good canonical way to
// represent a compile-time `bool`ean value.
template<typename T,typename=void> struct has_func : std::false_type {};
template<typename T> struct has_func<
  T,
  type_sink_t< decltype( std::declval<T&>().func() ) >
> : std::true_type {};

// helpers for tag dispatching.
namespace helper_ns {
  template<typename T> void anotherFunc( T&& t, std::false_type /* has_func */ ) {}
  template<typename T> void anotherFunc( T&& t, std::true_type /* has_func */ ) {
    std::forward<T>(t).func();
  }
}
// take the type T, determine if it has a .func() method.  Then tag dispatch
// to the correct implementation:
template<typename T> void anotherFunc(T t) {
  helper_ns::anotherFunc( std::forward<T>(t), has_func<T>() );
}

是一个 C++11 解决方案,它在特征类上进行标记分派(dispatch),确定 t.func() 是否为有效表达式。

关于c++ - 模板:只有在类有方法时才执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415285/

相关文章:

c++ - Linux 生成文件中的 undefined reference

c++ - 获取笛卡尔积的算法

C++11 从初始化列表到数组参数的隐式转换

c++ - SFINAE : Delete a function with the same prototype

c++ - VS 调试器中未正确显示具有嵌套类型的 QList

c++ - 将 std::sets 合并到 std::vector

c++ - 检查模板函数的数据类型

c++ - 如何专门化模板成员函数?

css - 模板中的 Golang ttf 字体

c++ - friend 类无法访问私有(private)数据