2010-10-02 197 views
1

爲什麼編譯器不能專門化這個函數,是否有辦法強制他這麼做?
我得到的錯誤:
錯誤1個錯誤C2893:無法專注函數模板'未知類型 '三元::檢查(BOOL,左,右)'
三元運算符

#include "stdafx.h" 
#include <iostream> 
#include <string> 
using std::cout; 
using std::string; 

template<int v> 
struct Int2Type 
{ 
    enum {value = v}; 
}; 

template<bool condition,class Left, class Right> 
struct Result; 


template<class Left, class Right> 
struct Result<true,Left,Right> 
{ 
    typedef Left value; 
}; 

template<class Left, class Right> 
struct Result<false,Left,Right> 
{ 
    typedef Right value; 
}; 

struct Ternary 
{ 
    template<class Left, class Right> 
    static Right check_(Int2Type<false>, Left left, Right right) 
    { 
     return right; 
    } 

    template<class Left, class Right> 
    static Left check_(Int2Type<true>, Left left, Right right) 
    { 
     return left; 
    } 


__Updated__ 
    template<bool Condition,class Left, class Right> 
static auto check(Left left, Right right)-> 
    typename Result<Condition,Left,Right>::value 
{ 
    return check_(Int2Type<Condition>,left,right); 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int a = 5; 
    string s = "Hello"; 
    cout << Ternary::check<false>(a,s); 
    return 0; 
} 
+0

@Prasoon Saurav C++ 03它可以被認爲是C++ 0x的一個「子集」,所以你的編輯不適合C++ 0x覆蓋它。 – 2010-10-02 12:08:17

+5

是的,但是SO並不那麼明亮。如果您搜索標有「C++」的問題,SO將不會列出此問題。 – 2010-10-02 12:12:32

+0

什麼是錯誤? – ybungalobill 2010-10-02 12:13:42

回答

3

我不「沒帶的C++ 0x足夠的經驗呢,但是從我所看到的:

decltype(Result<(sizeof(int) == 1),Left,Right>::value) 

decltype預期的表現,但Result<...>::value是一種類型。只要刪除decltype;

return check_(Int2Type<condition>,left,right); 

condition是一個變量,你不能使用它作爲模板參數。

UPDATE:Int2Type<Condition>也是一種類型。你想傳遞一個值:Int2Type<Condition>()

+0

@ybungalobill類似於sizeof運算符,decltype的操作數是未評估的[9]。非正式地,由decltype(e)返回的類型推導如下:[1] 如果表達式e在局部或命名空間作用域中引用__variable__,則爲靜態成員變量或函數參數,則結果爲變量的或參數的聲明類型 如果e是函數調用或重載操作符調用,則decltype(e)表示該函數的聲明返回類型 否則,如果e是左值,則decltype(e)是T&,其中T是Ë;如果e是一個右值,結果是T – 2010-10-02 12:21:17

+0

@There:它與評估無關。 **語法**表示括號之間的事物必須是**表達式**,您在那裏寫的是**類型**。 – ybungalobill 2010-10-02 12:25:09

+0

@ybungalobill好吧。但是我可以刪除decltype - 它不會編譯 – 2010-10-02 12:30:06