Троичный оператор - PullRequest
1 голос
/ 02 октября 2010

Почему компилятор не может специализировать эту функцию и есть ли способ заставить его сделать это?
Ошибка, которую я получаю:
Ошибка 1 ошибка C2893: Не удалось специализировать шаблон функции '' неизвестно'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 Ответ

3 голосов
/ 02 октября 2010

У меня пока недостаточно опыта работы с 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>().

...