5

このコード(クラスMのfnc値)がSFINAEルールによって解決されないのはなぜですか?エラーが発生しました:

Error   1   error C2039: 'type' : is not a member of
                                   'std::tr1::enable_if<_Test,_Type>'  

もちろん、typeはメンバーではなく、enable_ifのこの一般的なバージョンでは定義されていませんが、boolがtrueの場合にfncのこのバージョンを有効にし、falseの場合はインスタンス化しないというこの背後にある全体的な考え方ではありませんか?誰かが私にそれを説明してもらえますか?

#include <iostream>
#include <type_traits>

using namespace std;

template <class Ex> struct Null;
template <class Ex> struct Throw;

template <template <class> class Policy> struct IsThrow;

template <> struct IsThrow<Null> {
    enum {value = 0};
};

template <> struct IsThrow<Throw> {
    enum {value = 1};
};

template <template <class> class Derived>
struct PolicyBase {
    enum {value = IsThrow<Derived>::value};
};

template<class Ex>
struct Null : PolicyBase<Null> { };

template<class Ex>
struct Throw : PolicyBase<Throw> { } ;

template<template< class> class SomePolicy>
struct M {

  //template<class T>
  //struct D : SomePolicy<D<T>>
  //{
  //};
  static const int ist = SomePolicy<int>::value;
  typename std::enable_if<ist, void>::type value() const
  {
    cout << "Enabled";
  }

  typename std::enable_if<!ist, void>::type value() const
  {
    cout << "Disabled";
  }
};

int main()
{
    M<Null> m;
    m.value();
}
4

2 に答える 2

5

SFINAEは、非テンプレート関数では機能しません。代わりに、たとえば(クラスの)特殊化またはオーバーロードベースのディスパッチを使用できます。

template<template< class> class SomePolicy>
struct M
{
    static const int ist = SomePolicy<int>::value;        
    void value() const { 
        inner_value(std::integral_constant<bool,!!ist>()); 
    }
 private:
    void inner_value(std::true_type) const { cout << "Enabled"; }
    void inner_value(std::false_type) const { cout << "Disabled"; }
};
于 2010-11-12T12:57:41.547 に答える
3

ここにはsfinaeはありません

がわかった後M<Null>、変数istもわかります。次にstd::enable_if<ist, void>、明確に定義されています。関数の1つが明確に定義されていません。

SFINAEは、テンプレート関数の場合にのみ機能します。テンプレート関数はどこにありますか?

コードを次のように変更します

template<int> struct Int2Type {}

void value_help(Int2Type<true> ) const { 
    cout << "Enabled"; 
} 

void value_help(Int2Type<false> ) const { 
    cout << "Disabled"; 
} 

void value() const { 
    return value_help(Int2Type<ist>());
}
于 2010-11-12T12:55:36.617 に答える