2013-02-14 34 views
1

我從閱讀各種帖子瞭解到,以下是不應該編譯。enable_if +類型模板,沒有SFINAE(enable_if_c沒有提升?)

#include <type_traits> 
#include <iostream> 

template <bool is_constant> struct A { 
    // Need to fix this for g++-4.7.2 
    // implicit conversion to int iff is_constant == true statically 
    template <class = typename std::enable_if<is_constant>::type> 
    constexpr operator int() const { 
    return 10; 
    }            
}; 

int main() 
{ 
    A<true> a; 
    int i = 2 + a; 
    std::cout << i << "\n"; 

    A<false> b; 
    // int i = 2 + a; // compilation error 
} 

儘管如此,鐺3.2接受此代碼版本,並運行良好。我的理解是它使用內部版本的enable_if_c。 現在我想要在gcc下編譯這個不接受它的代碼。 我知道這將是一個很好的實際類型,並使用SFINAE作爲其他職位。

在我的情況:

  • 我試圖定義一個操作,所以我不能說有一些默認的類型/值額外的參數大驚小怪周圍 - >看來我不能用SFINAE。
  • 我不能使用繼承,因爲我必須保留所有的東西。
  • 我不能使用任何刺激包括在我的項目,因爲要求代碼(enable_if_c)

我有出路?

+1

怎麼樣'static_assert(is_constant)'? – borisbn 2013-02-14 03:33:46

+0

爲什麼'constexpr'意味着你不能使用繼承? – 2013-10-05 16:02:35

回答

0

爲什麼不使用專業化?

#include <iostream> 

template <bool is_constant> 
struct A {}; 

template <> 
struct A<true> { 
    constexpr operator int() const { 
     return 10; 
    } 
}; 

int main() 
{ 
    A<true> a; 
    int i = 2 + a; 
    std::cout << i << "\n"; 

    A<false> b; 
    // int ii = 2 + b; // compilation error 
} 

這是相當簡單和交叉編譯的方法...

+0

你知道嗎......爲什麼這不是?原來我的一段代碼變得如此複雜,以至於我失去了這個簡單選項的軌跡......我不得不復制一些代碼,因爲我無法繼承(字面類型和constexpr)。但至少現在我可以忍受!謝謝 ! – NickV 2013-02-14 03:55:33