我需要在模板类 (TC) 中实例化一个自由模板函数 (FTF)。 FTF将TC的模板参数之一作为模板参数。 TC 还保存指向这些 FTF 的通用指针,并且通过指针调用这些函数。
获取指向 FTF 的指针的步骤不足以实例化它,并且我收到来自 GCC 工具链的链接器错误。 MSDN 阐释了 FTF 规范 as so -- 然而,我的 FTF 实例化依赖于我的 TC 的模板参数,因此 FTF 实例化不能放置在自由范围中。
这可能吗?我附加了一些基本的生成代码,问题出在类 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*
的函数更简洁......
关于c++ - 在模板类中实例化自由模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6609705/