我显然误解了关于模板特化的一些重要内容,因为:
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
适用于整个类型。如果 type
是 char*
(如您的特化),则返回类型是 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/