C++ C+的模板专业化+;有常数
我显然误解了模板专门化的一些重要内容,因为:C++ C+的模板专业化+;有常数,c++,templates,template-specialization,C++,Templates,Template Specialization,我显然误解了模板专门化的一些重要内容,因为: template<typename type> const type getInfo(int i) { return 0; } template<> const char* getInfo<char*>(int i) { return nullptr; } 当 模板类型getInfo(inti){return 0;} 模板char*getInfo(inti){return nullptr;} 很好。如何将con
template<typename type> const type getInfo(int i) { return 0; }
template<> const char* getInfo<char*>(int i) { return nullptr; }
当
模板类型getInfo(inti){return 0;}
模板char*getInfo(inti){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; }
template const type getInfo(int i){return 0;}
模板char*const getInfo(int i){return nullptr;}
如果将类型专门化为指针,这是有意义的。为什么模板应该对指针指向的内容有发言权
但是,在这种情况下,我看不出有多少理由将返回类型设为
const
注意,在第一个示例中,返回类型是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; }
template const type getInfo(int i){return 0;}
模板char*const getInfo(int i){return nullptr;}
如果将类型专门化为指针,这是有意义的。为什么模板应该对指针指向的内容有发言权
但是,在这种情况下,我不认为有多少理由将返回类型设为
const
如果需要能够返回字符串常量,请使用以下命令:
template<typename type> type getInfo(int i) { return 0; }
template<> const char* getInfo<const char*>(int i) { return nullptr; }
这没有多大意义。如果您需要能够返回字符串常量,请使用以下命令:
template<typename type> type getInfo(int i) { return 0; }
template<> const char* getInfo<const char*>(int i) { return nullptr; }
这没有多大意义。sftrabbit的回答让我顿悟,明白了我的错误,但你的回答更符合我的实际需要,很抱歉,我不能同时接受这两个答案!兔子的回答让我顿悟,明白了我的错误,但你的回答更符合我的实际需要,很抱歉,我不能同时接受这两个答案!谢谢我迟早要把康斯特的规则固定下来。const返回类型的原因与原始代码有关。上面的版本是我对这个问题的最小复制,所以是的,它在这里不是很有用。谢谢。我迟早要把康斯特的规则固定下来。const返回类型的原因与原始代码有关。上面的版本是我对这个问题的最小复制,所以是的,它在这里不是很有用。
const int getInfo( int i ) { return 0; }