在模板类中实例化自由模板函数

instantiating a free template function within a template class

本文关键字:自由 函数 实例化      更新时间:2023-10-16

我需要在模板类(TC)中实例化一个自由模板函数(FTF)。FTF将TC的模板参数之一作为模板参数。TC还保存了指向这些FTF的泛型指针,这些函数可以通过这些指针调用。

获取指向FTF的指针的步骤不足以实例化它,并且我从GCC工具链收到链接器错误。MSDN就这样说明了FTF规范——然而,我的FTF实例依赖于我的TC的模板参数,因此FTF实例不能放在自由作用域中。

这可能吗?我附加了一些基本生成的代码,问题是在class test_service的构造函数中,我将自由函数的指针分配到自定义容器中。我得到一个链接器错误,告诉我无法找到自由函数(未实例化)。我知道在类的某个地方指定对模板函数的调用将产生一个实例化,但是我只打算通过指针进行调用。

#include "rpc_common.h"
#include <boost/cstdint.hpp>
namespace rubble { namespace rpc {
  struct test_service_dummy_tag{};
  template<typename T>
  class test_service_skel
  {
  public:
    bool Init() {}
    bool TearDown() {}
    bool test_one(TestRequest,TestResponse){};
  private:
  };
  template<typename T_IMPL>
  bool test_service_test_one(T_IMPL & impl,ClientRequest & request)
  {
    return 0;
  }
  template<typename T_IMPL=test_service_skel<test_service_dummy_tag> >
  class test_service
  {
  public:
    test_service()
    {
      // uncomment the following two lines and a instantiation will occur.
      // ClientRequest cr;
      //test_service_test_one<T_IMPL>(m_impl,cr);
      m_dispatch_table.SetEntry( Oid("test_one",0),(void *)  & test_service_test_one<T_IMPL>);
    }
    bool Init() { return m_impl.Init(); };
    bool TearDown() { return m_impl.TearDown(); };
  private:
    T_IMPL m_impl;
    OidContainer<Oid,void *> m_dispatch_table;
  };

} }

编辑:自包含的最小版本

 class test_skel
    {
      bool test_function()
      {
        return true;
      }
    };

    template<typename T>
    bool test_function()
    {
    }
    template<typename T = test_skel>
    class test
    {
    public:
      test()
      {
        dispatch = (void *) & test_function<T>;
      }
      void * dispatch;
    };
    int main()
    {
      test<> t;
      return 0;
    }

如果您不使用void*,也没有问题,即:http://www.ideone.com/eRgUG

然而,如果坚持将指针存储在void*中,那么您需要首先使用特定的函数指针获取地址,然后进行强制转换-例如

    bool (*temp)() = &test_function<T>;
    dispatch = reinterpret_cast<void*>(temp); // YUCK

给编译器足够的上下文为你生成地址。

啊-刚刚看到DeadMG的回答,生成void*的函数更简洁…

您的自包含示例不会为我编译一个关于重载函数的奇怪错误,当没有重载正在进行时,使用MSVC。不过,我还是设法解决了这个问题。

class test_skel
{
    bool test_function()
    {
        return true;
    }
};
template<typename T> void* to_void_pointer(T t) {
    return reinterpret_cast<void*>(t);
}
template<typename T>
bool test_function()
{
    return true;
}
template<typename T = test_skel>
class test
{
public:
    test()
    {
        dispatch = to_void_pointer(&test_function<T>);
    }
    void * dispatch;
};
int main()
{
    test<> t;
    return 0;
}

编译干净。我怀疑无论你看到什么行为,我看到的是一个编译器错误。