【发布时间】:2014-02-06 12:15:52
【问题描述】:
我面临以下问题:
我有 some 通用容器,它能够对类型进行 some 操作。为简单起见,这些操作在请求时是线程安全的。并且,requested to表示容器中的类型有typedef std::true_type needs_thread_safety;。
struct thread_safe_item {
typedef std::true_type needs_thread_safety;
/* */
};
struct thread_unsafe_item {
typedef std::false_type needs_thread_safety;
/* */
};
template<typename TItem> container {
/* some algorithms, that are std::enable_if selected, according to needs_thread_safety */
};
但是,我希望 needs_thread_safety 选择加入,并且不需要定义(= 默认 false_type)。我试过以下:
struct thread_unsafe_item {
/* */
};
template<typename TItem>
struct thread_safety_selector
{
template<typename T>
struct has_defined_thread_safety
{
typedef char yes[1];
typedef char no[2];
template <typename C> static yes& test(typename C::needs_thread_safety*);
template <typename> static no& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
typedef
typename std::conditional<
has_defined_thread_safety<TItem>::value,
typename TItem::needs_thread_safety,
std::false_type
>::type needs_thread_safety;
};
....
struct <typename TItem> container {
/* changed all TItem::needs_thread_safety selectors to thread_safety_selector<TItem>::needs_thread_safety */
};
但显然没有进行惰性评估,因为错误是error C2039: 'needs_thread_safety' : is not a member of 'thread_unsafe_item'。
如何实现未指定参数的默认值?
这是出于教育目的,所以我不需要不同的方法来解决这个问题。
谢谢!
【问题讨论】:
-
通常我使用类型选择器来指定我的最终类的特定基类,其中基类包含适当的实现。
标签: c++ templates c++11 metaprogramming