2010-11-12 33 views
5

爲什麼此代碼(類M中的fnc值)不能通過SFINAE規則解決?我發現了一個錯誤:SFINAE的問題

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

當然類型是不是會員,它不是在enable_if這種一般版本定義但不是這背後的整體思路,使FNC的這個版本,如果布爾是真的,如果它是假的,不要實例化它?可以請某人向我解釋?

#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(); 
} 

回答

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

沒有SFINAE這裏。

M<Null>已知變數ist也是已知的。 然後std::enable_if<ist, void>也是明確的。 你的一個功能沒有明確定義。

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