三元运算符

时间:2010-10-02 11:46:07

标签: c++ templates c++11 conditional-operator

为什么编译器不能专门化这个功能,有没有办法迫使他这样做? 我得到的错误:
错误1错误C2893:无法专门化功能模板''unknown-type'Ternary :: check(bool,Left,Right)'

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

1 个答案:

答案 0 :(得分:3)

我还没有足够的C ++ 0x经验,但从我看到的:

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

decltype需要一个表达式,但Result<...>::value是一种类型。只需删除decltype;

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

condition是一个变量,您不能将其用作模板参数。

更新:Int2Type<Condition>也是一种类型。您想传递一个值:Int2Type<Condition>()