[英]Specialize template for types that contain typedef
I have a template class that needs to be specialized for template parameters that contain specific typedef. 我有一个模板类,需要专门用于包含特定typedef的模板参数。 So I need two definitions, one for the case it has the typedef and another for the case it does not.
因此,我需要两个定义,一个用于具有typedef的情况,另一个用于不具有typedef的情况。
My problem is that I don't see how to negate the SFINAE. 我的问题是我看不到如何否决SFINAE。 I could obviously eliminate the special case for the non-special parameter, but I don't know how to eliminate the default for the special parameter.
我显然可以消除非特殊参数的特殊情况,但是我不知道如何消除特殊参数的默认情况。
So I tried partial specialization like this: 所以我尝试像这样的部分专业化:
struct NormalType { };
struct SpecialType { typedef int special; };
template <typename T, typename IsSpecial = void>
struct DetectSpecial {
void detected() { std::cout << "Not special...\n"; }
};
template <typename T>
struct DetectSpecial<T, typename T::special> {
void detected() { std::cout << "Special!\n"; }
};
but the specialization does not get used ( as SSCCE on ideone ). 但是没有使用专业化( 作为ideone上的SSCCE )。
I have also considered using enable_if
, but I don't see how to use it for well-formed vs. non-well-formed expressions rather than true/false. 我也考虑过使用
enable_if
,但是我看不到如何将其用于格式正确与格式错误的表达式,而不是true / false。
What is the simplest way to define DetectSpecial
differently for types that contain specific typedef (the value of the typedef may be anything; it's presence is important)? 为包含特定typedef的类型不同地定义
DetectSpecial
的最简单方法是什么(typedef的值可以是任何值;它的存在很重要)?
Oh, I am still stuck with some C++03 compilers. 哦,我仍然停留在某些C ++ 03编译器上。 I don't think anything change in SFINAE anyway.
我认为SFINAE不会发生任何变化。
The minimal change required is to insert some expression in the specialization that is dependent on T::special
and yields void
(to match the default argument). 所需的最小更改是在依赖
T::special
的专业化中插入一些表达式,并产生void
(以匹配默认参数)。 For example: 例如:
template<class T>
struct void_alias
{
typedef void type;
};
template <typename T>
struct DetectSpecial<T, typename void_alias<typename T::special>::type> {
void detected() { std::cout << "Special!\n"; }
};
Following may help: (C++11) https://ideone.com/XISlZ6 (C++03) https://ideone.com/egKrcL 以下内容可能会有所帮助:(C ++ 11) https://ideone.com/XISlZ6 (C ++ 03) https://ideone.com/egKrcL
#include <cstdint>
template <typename U>
class has_special
{
private:
template<typename T> struct dummy;
template<typename T>
static std::uint8_t check(dummy<typename T::special>*);
template<typename T> static std::uint16_t check(...);
public:
static
constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.