Dan*_*ica 20 c++ boost vector boost-mpl explicit-instantiation
请考虑以下头文件:
// Foo.h
class Foo {
    public: 
        template <typename T>
        void read(T& value);
};
我想Foo::read在源文件中显式实例化成员函数模板,包括在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编译器.)
我不确定这是否是您问题的解决方案,但也许您可以使用模板专业化。
新标题:
// Foo.h
template < typename T >
struct RealRead;
class Foo {
    public: 
        template <typename T>
        void read(T& value);
};
template <typename T>
void Foo::read(T& value)
{
  RealRead< T >::read( value );
}
新来源:
template < >
struct RealRead< int >
{
  static void read( int & v )
  {
    // do read
  }
};
template < >
struct RealRead< float >
{
  static void read( float & v )
  {
    // do read
  }
};
//etc
// explicitly instantiate templates
template struct RealRead< int >;
template struct RealRead< float >;
| 归档时间: | 
 | 
| 查看次数: | 2066 次 | 
| 最近记录: |