c++ - 使用 const 在 C++ 中进行模板特化

标签 c++ templates template-specialization

我显然误解了关于模板特化的一些重要内容,因为:

template<typename type> const type getInfo(int i) { return 0; }
template<> const char* getInfo<char*>(int i) { return nullptr; }

编译失败:

src/main.cpp:19:24: error: no function template matches function
        template specialization 'getInfo'

同时

template<typename type> type getInfo(int i) { return 0; }
template<> char* getInfo<char*>(int i) { return nullptr; }

工作正常。如何将 const 与模板特化一起使用?我的菜鸟错误是什么?

我在 clang++ 上使用 c++11。

最佳答案

请注意,在第一个示例中,返回类型是const type,因此const 适用于整个类型。如果 typechar*(如您的特化),则返回类型是 char * const。这编译得很好:

template<typename type> const type getInfo(int i) { return 0; }
template<> char* const getInfo<char*>(int i) { return nullptr; }

这是有道理的 - 如果将类型特化为指针。为什么模板应该对指针指向的内容有任何发言权?

但是,在这种情况下,我看不出有太多理由将返回类型设置为 const

关于c++ - 使用 const 在 C++ 中进行模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096084/

相关文章:

c++ - 无法推断模板参数( vector 、std::function)

javascript - 在 Ember.js 中将一个模板加载到另一个模板中

c++ - 如何使用模板模板参数专门化模板

c++ - 模板类型的奇怪行为

c++ - 为什么我不能将 lambda 转换为 void* 然后转换为函数指针?

c++ - 定义基于模板的映射指针,以便在验证范围时将 int 解析为 enum

c++ - 将准备好的语句与 sqlite 事务语句一起使用

c++ - 仅使用库 iostream 和 cstring 在字符串中查找单词

c++ - 使用可变参数模板的显式模板实例化

c++ - 在 A 或 B 的任何容器上重载模板成员函数