在一个C++模板函数内,我想调用另一个未声明的重载函数。由于该函数不是依赖项,编译器将无法解析它。
代码如下:
代码如下:
#include <array>
#include <iostream>
#include <string>
template <typename T>
void serialize(const T &data)
{
size_t data_size = getSize(data);
std::cout << "Size: " << data_size << std::endl;
}
constexpr size_t getSize(const int &)
{
return sizeof(int);
}
size_t getSize(const std::string &str)
{
return str.size();
}
template <typename T, size_t N>
size_t getSize(const std::array<T, N> &array)
{
size_t array_size = 0;
for (const T &element : array)
array_size += getSize(element);
return array_size;
}
int main()
{
int a;
serialize(a);
std::string str = "foo";
serialize(str);
std::array<std::string, 2> arr = {{"foo", "foobar"}};
serialize(arr);
return 0;
}
有没有好的方法使getSize()
变得有依赖性?或者还有其他实现方式吗?
getSize()
声明为模板函数,并为特定类型进行专门化。 - SlavagetSize()
函数用于数组? - Dino