C ++模板专门化,但没有找到匹配项

时间:2015-11-23 10:51:35

标签: c++ templates template-specialization specialization

我有一个反序列化功能。有了模板,我希望能够得到我反序列化的东西。换句话说,我喜欢计算序列化事物的函数和处理反序列化的函数。如果我以不同的方式命名它们,我没有问题,而且,实际上,这是一个非常简单的解决方案,我肯定会这样做。但令我困扰的是,我不明白为什么以下内容是不可接受的。

#include <string>

using std::string;

// In real life, fetch the stringified object.
template<>
string foo(int x);

// In real life, fetch an object and deserialize it.
template <typename T>
T foo(int x) {
    string s = foo<string>(x);
    T t;
    // Do something with s.
    return t;
}

template<>
string foo(int x) { return std::to_string(x); }

使用

进行编译
clang -Wall -Wextra -std=c++14 foo.cc -o foo

foo.cc:6:8: error: no function template matches function template specialization 'foo'
string foo(int x);

所以显而易见的解决方案就是将第一个函数更改为string make_foo(int x)并完成它。

为了帮助我学习,我一直试图理解为什么我上面写的内容失败了。请注意,我也尝试了template <> string foo<string>(int x),但我认为可以推断出专业化。

0 个答案:

没有答案