免责声明 - 老实说,我不知道如何设置这个问题或提供适当的上下文,并希望如果有人遇到这个问题可以推荐什么额外的信息,我需要提供给澄清背景。而且,如果我需要清理下面的代码部分以使其更清晰,我会在收到评论时这样做!编译器在C++中跳过可变参数模板/函数
但无论如何,在这里去 -
我试图用可变参数模板工作,但每次我编译我的代码(其对公司的代码库)的编译器(gcc 4.8.4 - C++ 11)似乎跳过在所有的可变参数的代码段 -
TestFactory.cpp
/*
* Use this design since Variadic Templates are not available in C++11
* A MapHolder allows us to create a map of variadic functions.
*/
template <class... Args>
struct MapHolder
{
static std::map<std::string, NpBaseTest*(*)(Args...)> CallbackMap;
};
template <class... Args>
std::map<std::string, NpBaseTest *(*)(Args...)> MapHolder<Args...>::CallbackMap;
class TestFactory
{
public:
template <class... Args>
static void RegisterTest(std::string name, NpBaseTest *(*callback)(Args...));
template <class... Args>
static NpBaseTest *CreateTest(const std::string &name, Args &&... args);
};
TestFactory.cpp
template <class... Args>
void TestFactory::RegisterTest(std::string name, NpBaseTest *(*callback)(Args...))
{
MapHolder<Args...>::CallbackMap[name] = callback;
}
template <class... Args>
NpBaseTest *TestFactory::CreateTest(const std::string &name, Args &&... args)
{
return (MapHolder<Args...>::CallbackMap[name])(std::forward<Args>(args)...);
}
调用文件 -
void np_test_mgr_print()
{
const char *s = "cavpkotest";
std::string str(s);
TestFactory::RegisterTest(str.c_str(), &CavPkoTest::create);
NpBaseTest *o1{TestFactory::CreateTest<uint16_t>(str.c_str(), 1)};
/* Irrelevant code section */
NpTestMgr::get_instance().insert(o1);
NpTestMgr::get_instance().submit();
}
}
当我编译这个(GCC 4.8.4)的目标文件TestFactory.o是空的。如果我这样做,我们的代码库外(GCC 4.4.6)的代码被编译和输出 -
[common]$ nm TestFactory.o | c++filt $1 | grep CreateTest
34:0000000000401d6a W NpBaseTest* TestFactory::CreateTest<unsigned short>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned short&&)
[common]$ nm TestFactory.o | c++filt $1 | grep RegisterTest
35:0000000000401d40 W void TestFactory::RegisterTest<unsigned short>(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, NpBaseTest* (*)(unsigned short))
是否有'c'-tag的原因还是只是觉得它美观? – EOF
模板仅在使用时实例化*。将该定义放在实现中而不使用*在该文件中*将导致不实例化。然后,当您尝试在其他地方使用它时,它将找不到要实例化的实现,因为它位于当前翻译单元无法看到的实现文件中。你应该在头文件中保留实现。 [看到这个问题](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)。 –
@FrançoisAndrieux我会给你一个机会,并提供更新!感谢您的链接! – nitimalh