Ian*_*Ian 1 c++ templates template-specialization
我显然误解了关于模板特化的重要事项,因为:
template<typename type> const type getInfo(int i) { return 0; }
template<> const char* getInfo<char*>(int i) { return nullptr; }
Run Code Online (Sandbox Code Playgroud)
无法编译:
src/main.cpp:19:24: error: no function template matches function
template specialization 'getInfo'
Run Code Online (Sandbox Code Playgroud)
而
template<typename type> type getInfo(int i) { return 0; }
template<> char* getInfo<char*>(int i) { return nullptr; }
Run Code Online (Sandbox Code Playgroud)
工作良好.如何使用const模板专业化?我的菜鸟错误是什么?
我在clang ++上使用c ++ 11.
请注意,在第一个示例中,返回类型是const type,因此const适用于整个类型.如果type是char*(如你的专业化),那么返回类型是a char * const.编译得很好:
template<typename type> const type getInfo(int i) { return 0; }
template<> char* const getInfo<char*>(int i) { return nullptr; }
Run Code Online (Sandbox Code Playgroud)
这是有道理的 - 如果将类型专门化为指针.为什么模板对指针指向的内容有任何发言权?
但是,在这种情况下,我没有太多理由认为返回类型是const.