我正在研究Visual Studio 2015 community edition
假设我有一个简单的类,如下所示:
(下面的示例"应该是"可编译的,因为它包含所有必要的东西,不幸的是,它会产生错误(。
#include <stdexcept>
template <typename T>
class class_foo
{
// members, methods, constructors. not important stuff...
// helper functions:
private:
class tag_aaa {}; // to resolve few things at compile-time, not run-time.
class tag_bbb {}; // - || -
template <typename tag>
void erase();
// for some reason this is not interpreted as an error by my compiler:
template<>
void erase<tag_aaa>();
template<>
void erase<tag_bbb>();
};
// catch-all-do-nothing "version"
// well, catch-all-throw-an-exception because call to this function is an obvious error.
// that should never occur.
template <typename T>
template <typename tag> inline
void class_foo<T>::erase()
{
throw std::runtime_error("Very weird error...");
}
template <>
template <typename T> inline
void class_foo<T>::erase<class_foo<T>::tag_aaa>()
{
// do some stuff...
}
template <>
template <typename T> inline
void class_foo<T>::erase<class_foo<T>::tag_bbb>()
{
// do some stuff...
}
int main()
{
class_foo<double> bar;
return 0;
}
错误:
1>D:/develop/workspace/visual_studio/nevada_test_site/source/workspace/nevada_test_site/start.cu(36): error : partial specialization of class "class_foo<T>::erase<class_foo<T>::tag_aaa> [with T=T]" is not allowed
1>D:/develop/workspace/visual_studio/nevada_test_site/source/workspace/nevada_test_site/start.cu(43): error : partial specialization of class "class_foo<T>::erase<class_foo<T>::tag_bbb> [with T=T]" is not allowed
1>D:/develop/workspace/visual_studio/nevada_test_site/source/workspace/nevada_test_site/start.cu(51): warning : variable "bar" was declared but never referenced
我认为自己是一个初级业余程序员,所以我肯定错了,但我相信erase<class_foo<T>::tag_aaa>()
和erase<class_foo<T>::tag_bbb>()
都是template <typename tag> void erase();
功能的明确专业化。因此,它们是允许的。我相信此错误是由于一些错误的语法造成的,但我找不到错误。
问题:
- 我想要做的事情是允许的吗?
- 如果是,我做错了什么?
- 如果是,专门处理此功能(
erase
(的正确语法是什么?
它看起来像模板函数的完全专用化,但它仍然是部分专用化,因此编译错误。
这是为什么呢?好吧,看看这个专业化:
template <>
template <typename T>
inline void class_foo<T>::erase<class_foo<T>::tag_bbb>() {
// do some stuff...
}
你说这是一个明确的专业化,但仍然有一个模板参数需要填写!参数T
未知。所以专业化...那还是模板?这是部分专业化!
出于多种原因,不允许对功能进行部分专业化。其中之一是它不会很好地与重载配合。
为了有效地使函数专用化,您必须不留下任何模板参数,如下所示:
template<>
template<>
inline void class_foo<int>::erase<class_foo<int>::tag_bbb>() {
// do some stuff...
}
但这不是你想要的。
这是我解决这个问题的方法。使用重载而不是专用化:
template<typename T>
struct class_foo {
private:
struct tag_aaa {};
struct tag_bbb {};
void erase(tag_aaa) {
// Stuff when tag_aaa
}
void erase(tag_bbb) {
// Stuff when tag_bbb
}
};
而不是像这样调用那些:
erase<tag_aaa>(); // with specialization
您必须像这样调用它:
erase(tag_aaa{}); // with overloading