[英]template behavior based on existence of a function
我有一个模板类foo
template <typename Item>
class foo
{
void method()
{
// ...
}
}
我需要的是基于Item类型更改方法的实现,基于是否存在说unsigned int hasher(const Item& item)
。
我的问题是-从技术上讲这怎么可能?如果没有,我如何组织代码来实现这一点?
请注意,性能对于算法来说意义重大,我正在寻找能够使编译器解决差异编译时间的解决方案。
您需要应用模板策略,看看: http : //en.wikipedia.org/wiki/Policy-based_design也是C ++模板
// Macro helper to create traits
#define HAS_TEMPLATED_FUNC(traitsName, funcName, Prototype) \
namespace detail { \
template<typename U> \
class traitsName \
{ \
typedef std::uint8_t yes; \
typedef std::uint16_t no; \
template <typename T, T> struct type_check; \
template <typename T = U> static yes &chk(type_check<Prototype, &funcName>*); \
template <typename > static no &chk(...); \
public: \
static bool const value = sizeof(chk<U>(0)) == sizeof(yes); \
}; \
} \
template <typename U> \
struct traitsName : std::conditional<detail::traitsName<U>::value, \
std::true_type, std::false_type>::type {}
现在假设:
unsigned int hasher(const int& item);
现在创建特征:
HAS_TEMPLATED_FUNC(has_hasher, hasher, unsigned int (*)(const T&));
// some test.
static_assert(has_hasher<int>::value, "");
static_assert(!has_hasher<char>::value, "");
现在,有一些使用方法
标签派发:
template <typename Item>
class foo
{
public:
void method()
{
method(has_hasher<Item>());
}
private:
void method(std::true_type)
{
// You may use hasher here.
hasher(Item{});
}
void method(std::false_type)
{
// You cannot use hasher here.
}
};
或SFINAE:
template <typename Item>
class foo
{
public:
template <typename T = Item>
typename std::enable_if<has_hasher<T>::value, void>::type
method()
{
// You may use hasher here.
hasher(Item{});
}
template <typename T = Item>
typename std::enable_if<!has_hasher<T>::value, void>::type
method()
{
// You cannot use hasher here.
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.