2016-03-03 62 views
0

我一直在試驗條件數據類型的boost頭文件。我將使用std::conditional,但我需要向後兼容非C++ 11編譯器。C++ boost條件類型不接受函數參數

因此,如果我在函數中明確聲明const int,以下工作。

#include <iostream> 
#include <typeinfo> 
#include <boost/mpl/if.hpp> 

using namespace boost::mpl; 

void f() 
{ 

    const int j = 1; 
    typedef typename if_c<j == 1, float, int>::type condType; 

    condType a; 

    std::cout << typeid(a).name() << std::endl; 

} 

int main() 
{ 
    f(); 

    return 0; 
} 

我最初以爲我會嘗試將const int傳遞作爲函數參數,但我得到一個編譯錯誤(見問題的結束)。

void f(const int i) 
{ 

    typedef typename if_c<i == 1, float, int>::type condType; 

    condType a; 

    std::cout << typeid(a).name() << std::endl; 

} 

我從這個question,我真的不能在函數參數const教訓。所以我也試着在論點上聲明一個const int

void f(int i) 
{ 
    const int j = i; 

    typedef typename if_c<j == 1, float, int>::type condType; 

    condType a; 

    std::cout << typeid(a).name() << std::endl; 

} 

但我繼續得到編譯錯誤。

boost_test.cpp: In function ‘void f(int)’: boost_test.cpp:11:25: error: ‘j’ cannot appear in a constant-expression typedef typename if_c::type condType;

有關如何將參數傳遞給有條件地設置類型的函數的任何想法?

+0

你不能,因爲函數參數在編譯時不知道。您可以改爲創建模板功能。 – interjay

回答

2

編譯器需要知道的i值時,這條線

typedef typename if_c<i == 1, float, int>::type condType; 

編譯。由於i是該函數的參數,因此編譯器無法預測參數將會變爲什麼,並且無法編譯您的函數。

您可以使用模板功能(以int i作爲模板參數)來實現您想要的功能。

例如:

template<int i> void f() { 
    typedef typename if_c<i == 1, float, int>::type condType; 

    condType a; 
    std::cout << typeid(a).name() << "\n"; 
} 

int main() 
{ 
    f<1>(); 

    return 0; 
} 
+0

謝謝,你能提供一個這樣的模板功能的例子嗎? – cdeterman

+0

@cdeterman,你在這裏 – SergeyA

+0

太好了,謝謝你的幫助 – cdeterman