Re[21]: Индекс по типу
От: B0FEE664  
Дата: 07.04.16 14:26
Оценка: +1
Здравствуйте, _hum_, Вы писали:

__>>>>>Люди хотят, чтобы перенумерованы были типы, которые отличаются операционной семантикой. Людям все равно, как называется тип, главное уверенность, что если номер одинаковый, то типы будут всюду в коде вести себя одинаково.

__>>>вот вы все говорите "легко" и "фигня", а так ни разу еще даже набросок решения не показали

BFE>>Набросок давно лежит рядом
Автор: B0FEE664
Дата: 29.03.16

BFE>>проверка здесь

__>да, прием интересный, но все равно еще же и морока с реализацией

__>
__>cast_to_fundamental_type(fundamental_type_id, val)
__>

__>будет.

Вы уж определитесь с набором операций и требований, а то складывается впечатление, что вы сами не знаете, чего вам надо:

#include <iostream>

template<int id> 
struct IdToType
{
    typedef void type;
    static const int s_nTypeId = -1;
};


template<class T> 
struct TypeToId
{
    typedef T type;
    static const int s_nTypeId = -1;
};


template<> struct IdToType<1>    {typedef int   type; static const int s_nTypeId = 1;};
template<> struct TypeToId<int>  {typedef int   type; static const int s_nTypeId = 1;};
                                                
template<> struct IdToType<2>    {typedef char  type; static const int s_nTypeId = 2;};
template<> struct TypeToId<char> {typedef char  type; static const int s_nTypeId = 2;};
                                 
template<> struct IdToType<3>    {typedef short type; static const int s_nTypeId = 3;};
template<> struct TypeToId<short>{typedef short type; static const int s_nTypeId = 3;};

template<> struct IdToType<4>    {typedef float type; static const int s_nTypeId = 4;};
template<> struct TypeToId<float>{typedef float type; static const int s_nTypeId = 4;};


int main(int argc, char* argv[])
{
    std::cout << "id of int = "   << TypeToId<int>::s_nTypeId   << std::endl;
    std::cout << "id of float = " << TypeToId<float>::s_nTypeId << std::endl;

    float f = 97.234f;
    IdToType<1>::type n = static_cast<IdToType<1>::type>(f);

    std::cout << "n = " << n << std::endl;

    auto ch = static_cast<IdToType<TypeToId<char>::s_nTypeId>::type>(f);
    std::cout << "ch = " << ch << std::endl;

    return 0;
}



id of int = 1
id of float = 4
n = 97
ch = a
И каждый день — без права на ошибку...
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.