考虑以下头文件:
// Foo.h
class Foo {
public:
template <typename T>
void read(T& value);
};
我想Foo::read
在源文件中为 a 中包含的所有类型显式实例化成员函数模板boost::mpl::vector
:
// Foo.cc
#include <boost/mpl/vector.hpp>
#include <boost/mpl/begin_end.hpp>
#include "Foo.h"
template <typename T>
void Foo::read(T& value) { /* do something */ }
typedef boost::mpl::vector<int, long, float> types;
// template Foo::read<int >(int&);
// template Foo::read<long >(long&);
// template Foo::read<float>(float&);
// instantiate automatically ???
可能吗?在此先感谢,丹尼尔。
编辑
我找到了一些解决方案 - 似乎Foo::read<T>
在结构的构造函数中分配一个指针,然后声明其中的变量,导致实例化:
// intermezzo
template <typename T> struct Bar {
Bar<T>() {
void (Foo::*funPtr)(T&) = &Foo::read<T>;
}
};
static Bar<int > bar1;
static Bar<long > bar2;
static Bar<float> bar3;
因此,该过程可以自动化如下:
// Foo.cc continued
template <typename B, typename E>
struct my_for_each {
my_for_each<B, E>() {
typedef typename B::type T; // vector member
typedef void (Foo::*FunPtr)(T&); // pointer to Foo member function
FunPtr funPtr = &Foo::read<T>; // cause instantiation?
}
my_for_each<typename boost::mpl::next<B>::type, E> next;
};
template<typename E>
struct my_for_each<E, E> {};
static my_for_each< boost::mpl::begin<types>::type,
boost::mpl::end<types>::type > first;
但我不知道这个解决方案是否可移植且符合标准?(适用于 Intel 和 GNU 编译器。)