c++ - const char* 的模板方法特化

标签 c++ templates template-specialization specialization

考虑这个片段:

struct S {
    template <typename T>
    void insert(const T& x);
};

template <>
void S::insert<char*>(const char*& x) {}

int main() {
    S s;
    s.insert("");
    return 0;
}

gcc 编译失败,错误信息如下:

error: template-id 'insert<char*>' for 'void S::insert(const char*&)' does not match any template declaration

此错误的原因是什么,是否有一种方法可以编写专用化使其正常工作?

我不是在寻找替代解决方案,我只是想了解错误背后的逻辑。

最佳答案

您指定了错误的参数类型。

请注意,对于 const T&constT 本身上是合格的。那么对于T = char*const T&应该是char* const &(即引用 const 指针),而不是 const char* &(即对指向 const 的指针的引用)。

顺便说一句 Clang给出更清晰的错误信息:

candidate template ignored: could not match 'void (char *const &)' against 'void (const char *&)'


顺便说一句,对于 s.insert(""); 规范不会被调用,因为 "" 是一个 const char[1] 确实如此,那么 T 的类型将被推断为 char [1],这与 char * 不匹配。如果您希望规范适用于 char[1],那么它应该是

template <>
void S::insert<char[1]>(char const (&) [1]) {}

然后

S s;
s.insert("");

但它只适用于 char[1],即只有一个元素的 char 数组。我认为让它与 const char* 一起工作会更有意义,那么它应该是

template <>
void S::insert<const char*>(const char * const &) {}

然后

S s;
const char* str = "";
s.insert(str);

关于c++ - const char* 的模板方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398728/

相关文章:

c++ - 如何编写没有参数包的可变参数函数?

c++ - clang (c++) 在特化中找不到名称

c++ - 如何通过在 C++ linux 中将其名称传递给变量来打开文件

c++ - Matlab 与 Visual C++?

c++ - 读取 Matrix txt 文件并存储为数组

c++ - 为什么标准禁止部分特化的友元声明?

c++ - 有多少个模板实例化?

c++ - 在 C++ 类中定义私有(private)变量/属性

c++ - 使用指针作为返回类型实现模板化接口(interface)的函数 -> 冲突返回类型错误

c++ - 为可迭代对象定义模板运算符<<