基于类成员的存在/缺乏专门化C ++模板? [英] Specializing C++ template based on presence/absense of a class member?
问题描述
请考虑以下内容:
struct A {
typedef int foo;
};
struct B {};
template< class T,bool has_foo = / * ??? * />
struct C {};
我想要专门化C,以便C<得到一个专门化,并且C<基于类型名称T :: foo的存在或不存在获得另一个。这是可能使用类型traits或一些其他模板魔术吗?
问题是,我试过的每一个实例化C< B&因为B :: foo不存在。但这是我想测试的!
编辑:
我认为ildjarn的答案更好,想出了以下C ++ 11解决方案。男人是黑客,但至少它的短。 :)
模板< class T&
constexpr typename T :: foo * has_foo(T *){
return(typename T :: foo *)1;
}
constexpr bool has_foo(...){
return false;
}
template< class T,bool has_foo =(bool)has_foo((T *)0)>另一种(C ++ 03)方法: p>
模板< typename T>
struct has_foo
{
private:
typedef char no;
struct yes {no m [2]; };
static T * make();
template< typename U>
static yes check(U *,typename U :: foo * = 0);
static no check(...);
public:
static bool const value = sizeof(check(make()))== sizeof(yes);
};
struct A
{
typedef int foo;
};
struct B {};
template< typename T,bool HasFooB = has_foo< T> :: value>
struct C
{
// T has foo
};
template< typename T>
struct C< T,false>
{
// T没有foo
};
Consider the following:
struct A {
typedef int foo;
};
struct B {};
template<class T, bool has_foo = /* ??? */>
struct C {};
I want to specialize C so that C<A> gets one specialization and C<B> gets the other, based on the presence or absence of typename T::foo. Is this possible using type traits or some other template magic?
The problem is that everything I've tried produces a compile error when instantiating C<B> because B::foo doesn't exist. But that's what I want to test!
Edit:
I think ildjarn's answer is better, but I finally came up with the following C++11 solution. Man is it hacky, but at least it's short. :)
template<class T>
constexpr typename T::foo* has_foo(T*) {
return (typename T::foo*) 1;
}
constexpr bool has_foo(...) {
return false;
}
template<class T, bool has_foo = (bool) has_foo((T*)0)>
解决方案 Another (C++03) approach:
template<typename T>
struct has_foo
{
private:
typedef char no;
struct yes { no m[2]; };
static T* make();
template<typename U>
static yes check(U*, typename U::foo* = 0);
static no check(...);
public:
static bool const value = sizeof(check(make())) == sizeof(yes);
};
struct A
{
typedef int foo;
};
struct B { };
template<typename T, bool HasFooB = has_foo<T>::value>
struct C
{
// T has foo
};
template<typename T>
struct C<T, false>
{
// T has no foo
};
这篇关于基于类成员的存在/缺乏专门化C ++模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!