在模板类中实例化自由模板函数
instantiating a free template function within a template class
我需要在模板类(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;
}
编译干净。我怀疑无论你看到什么行为,我看到的是一个编译器错误。
相关文章:
- 将自由函数绑定为类成员函数
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 为什么成员函数地址离自由函数这么远?
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 如何在共享库中保留静态库中的自由函数
- 在C++项目中管理自由函数有哪些好的做法?
- 使用自由函数作为LPOVELAPPED_COMPLETION_ROUTINE
- 统一检查成员函数、自由函数和算子是否存在的方式
- 使自由函数的行为类似于成员函数 (C++)
- C++自由函数可以别名吗?
- 调用成员函数(如果存在),回退到自由函数,反之亦然
- ADL找不到模板化的自由函数
- 基于方法或自由函数存在的模板构造函数解析
- G 未定义的引用自由函数
- 为什么未调用自由函数作为构造函数中的参数传递
- 自由函数和继承
- 调用自由函数而不是方法(如果不存在)
- 如何将自由函数与对象一起使用
- 如何使用begin()自由函数