簡體   English   中英

基於類成員的存在/缺席專門化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 <A>獲得一個特化,C <B>獲得另一個,基於typename T :: foo的存在與否。 這可能是使用類型特征或其他模板魔術嗎?

問題是我嘗試的所有內容在實例化C <B>時都會產生編譯錯誤,因為B :: foo不存在。 但這就是我想要測試的!


編輯:我認為ildjarn的答案更好,但我終於提出了以下C ++ 11解決方案。 男人是hacky,但至少它很短。 :)

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)>

另一種(C ++ 03)方法:

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
};

這樣的事情可能會有所幫助: has_member

typedef char (&no_tag)[1]; 
typedef char (&yes_tag)[2];

template< typename T > no_tag has_member_foo_helper(...);

template< typename T > yes_tag has_member_foo_helper(int, void (T::*)() = &T::foo);

template< typename T > struct has_member_foo {
    BOOST_STATIC_CONSTANT(bool
        , value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
        ); }; 

template<class T, bool has_foo = has_member_foo<T>::value> 
struct C {};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM