1

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

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。

4

2 回答 2

5

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

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

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

但是,在这种情况下,我认为没有太多理由让返回类型 be const

于 2013-02-26T18:05:17.650 回答
1

如果您需要能够返回字符串常量,只需使用以下命令:

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

你试图做的是这样的:

const int getInfo( int i ) { return 0; }

这没有多大意义。

于 2013-02-26T18:13:01.310 回答