LD 找不到生成的函数

ld cannot find generated function

本文关键字:函数 找不到 LD      更新时间:2023-10-16

我的代码:

#include <string>
template <typename ...KVs>
const std::string BuildJson(KVs... kvs);
template <typename ...AnotherKVs>
const std::string BuildJson(const std::string& key, const char* value, const std::string& nextkey, AnotherKVs... kvs)
{
std::string building = """ + key + "": ";
building += (value + ',' + BuildJson(nextkey, kvs...));
return building;
}
template <typename T, typename ...AnotherKVs>
const std::string BuildJson(const std::string& key, T value, const std::string& nextkey, AnotherKVs... kvs)
{
std::string building = """ + key + "": ";
building += (std::to_string(value) + ',' + BuildJson(key, kvs...));
return building;
}
template <>
const std::string BuildJson(const std::string& key, const char* value)
{
std::string building = """ + key + "": ";
building += value;
return building;
}
template <typename T>
const std::string BuildJson(const std::string& key, T value)
{
std::string building = """ + key + "": ";
building += std::to_string(value);
return building;
}
template <>
const std::string BuildJson() { return std::string(); }
int main(int argc, char* argv[])
{
BuildJson(
"key1", "value1",
"key2", 10000,
"key3", 10000.6999
);
return 0;
} 

/usr/bin/ld: /tmp/ccReTAIo.o: in function `main':
template_build_json.cpp:(.text+0x11c): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const BuildJson<char const*, char const*, char const*, int, char const*, double>(char const*, char const*, char const*, int, char const*, double)'
collect2: error: ld returned 1 exit status

如果把BuildJson(const std::string& key, T value)放在BuildJson(const std::string& key, const char* value)G++ 之前,G++ 会说:

template_build_json.cpp:33:19: error: ambiguous template specialization ‘BuildJson<>’ for ‘const string BuildJson(const string&, const char*)’
33 | const std::string BuildJson(const std::string& key, const char* value)

为什么ld找不到刚刚生成的函数?

包可以是空的。

取而代之的是:

template <typename ...AnotherKVs>
const std::string BuildJson(const std::string& key, const char* value, AnotherKVs... kvs)
template <typename T, typename ...AnotherKVs>
const std::string BuildJson(const std::string& key, T value, AnotherKVs... kvs)

尝试这样的事情:

template <typename... Tail>
const std::string BuildJson(const std::string& key, const char* value, const std::string& nextKey, Tail... tail)
template <typename T, typename... Tail>
const std::string BuildJson(const std::string& key, T value, const std::string& nextKey, Tail... tail)

例如

building += (std::to_string(value) + ',' + BuildJson(nextKey, tail...));

这要求这些"有更多参数"的情况确实具有更多参数(至少一个,nextKey参数(。

还要考虑完美转发,返回const值或多或少毫无意义。