Специализация шаблона в .cpp
От: _nn_ www.nemerleweb.com
Дата: 02.05.06 15:18
Оценка:
Допустим есть шаблонный класс и известно количество специализаций.
Можно эти специализации реализовать в .cpp через шаблонный класс:
// a.h
// Real implementation
template<typename T>
struct ax
{
 void f(T t);
};

// Specializations implementation
struct aint : ax<int>
{
 typedef ax<int> base;
 void f(int t);
};

struct along : ax<long>
{
 typedef ax<long> base;
 void f(long t);
};

// Selector
// Можно через mpl::if_<is_same...>
template<typename T>
struct a_selector;

template<>
struct a_selector<int>
{
 typedef aint type;
};

template<>
struct a_selector<long>
{
 typedef along type;
};

// Class Template
template<typename T>
struct a  : a_selector<T>::type
{
};

// a.cpp
#include <iostream>

// Real implementation
template<typename T>
void ax<T>::f(T t)
{
 std::cout << t << "\n";
}

// Specializations implementation
void aint::f(int t)
{
 base::f(t);
}

void along::f(long t)
{
 base::f(t);
}

// main.cpp
#include "a.h"

int main()
{
 a<int> x;
 x.f(1);

 a<long> y;
 y.f(1L);
}


В main.cpp используется шаблонный класс, в a.cpp реализация самого шаблона и классы прослойки для перехода из a.h в a.cpp.

Недостатки:
  • Нужно писать полное объявление специализированного класса.
  • Нужно писать реализацию методов класса.

    Сообственно вопрос состоит в том как недостатки убрать, например с помощью препроцессора
  • http://rsdn.nemerleweb.com
    http://nemerleweb.com
     
    Подождите ...
    Wait...
    Пока на собственное сообщение не было ответов, его можно удалить.