not*_*row 6 c++ templates metaprogramming c++11
我面临以下问题:
我有一些通用容器,可以对类型进行一些操作.为简单起见,操作在请求时是线程安全的.并且,要求表示容器中的类型具有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 */
};
Run Code Online (Sandbox Code Playgroud)
但是,我希望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 */
};
Run Code Online (Sandbox Code Playgroud)
但显然没有懒惰评估,因为错误是error C2039: 'needs_thread_safety' : is not a member of 'thread_unsafe_item'.
如何为未指定的参数实现默认值?
它是出于教育目的,所以我不需要不同的方法来解决这个问题.
谢谢!
你无法使用std::conditional它,因为它总是会解析它的所有参数.您可以创建自己的谓词:
template <bool, class>
struct get_thread_safety;
template <class T>
struct get_thread_safety<true, T>
{
typedef typename T::needs_thread_safety type;
};
template <class T>
struct get_thread_safety<false, T>
{
typedef std::false_type type;
};
// Used like this:
typedef
typename get_thread_safety<
has_defined_thread_safety<TItem>::value,
TItem
>::type needs_thread_safety;
Run Code Online (Sandbox Code Playgroud)