C++ 98 中的部分模板专业化?
Partial Template Specialization in C++ 98?
C++ 98 是否支持部分模板规范?
以下代码在 C++ 11 下编译良好,但在 Visual C++ 6.0 下无法编译。
所以我想知道语法是否需要稍微不同或者它是否不受支持:
#include <iostream>
#include <string>
template <typename A, typename B> class Foo
{
public:
static void bar(A a, B b)
{
std::cout << "A";
};
};
template <typename A> class Foo<A, std::string>
{
public:
static void bar(A a, std::string b)
{
std::cout << "B";
};
};
template <typename B> class Foo<std::string, B>
{
public:
static void bar(std::string a, B b)
{
std::cout << "C";
};
};
template <> class Foo<std::string, std::string>
{
public:
static void bar(std::string a, std::string b)
{
std::cout << "D";
};
};
int main(int argc, char* argv[])
{
Foo<int, int>::bar(12, 42);
Foo<int, std::string>::bar(12, "");
Foo<std::string, int>::bar("", 42);
Foo<std::string, std::string>::bar("", "");
return 0;
}
错误信息:
Compiling...
Test.cpp
C:\test\test.cpp(20) : error C2989: 'Foo<A,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >' : template class has already been defined as a non-template class
C:\test\test.cpp(20) : error C2988: unrecognizable template declaration/definition
C:\test\test.cpp(29) : error C2989: 'Foo<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,A>' : template class has already been defined as a non-template class
C:\test\test.cpp(29) : error C2988: unrecognizable template declaration/definition
Error executing cl.exe.
Test.obj - 4 error(s), 0 warning(s)
C++ 98 是否支持部分模板规范?
以下代码在 C++ 11 下编译良好,但在 Visual C++ 6.0 下无法编译。
所以我想知道语法是否需要稍微不同或者它是否不受支持:
#include <iostream>
#include <string>
template <typename A, typename B> class Foo
{
public:
static void bar(A a, B b)
{
std::cout << "A";
};
};
template <typename A> class Foo<A, std::string>
{
public:
static void bar(A a, std::string b)
{
std::cout << "B";
};
};
template <typename B> class Foo<std::string, B>
{
public:
static void bar(std::string a, B b)
{
std::cout << "C";
};
};
template <> class Foo<std::string, std::string>
{
public:
static void bar(std::string a, std::string b)
{
std::cout << "D";
};
};
int main(int argc, char* argv[])
{
Foo<int, int>::bar(12, 42);
Foo<int, std::string>::bar(12, "");
Foo<std::string, int>::bar("", 42);
Foo<std::string, std::string>::bar("", "");
return 0;
}
错误信息:
Compiling...
Test.cpp
C:\test\test.cpp(20) : error C2989: 'Foo<A,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >' : template class has already been defined as a non-template class
C:\test\test.cpp(20) : error C2988: unrecognizable template declaration/definition
C:\test\test.cpp(29) : error C2989: 'Foo<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,A>' : template class has already been defined as a non-template class
C:\test\test.cpp(29) : error C2988: unrecognizable template declaration/definition
Error executing cl.exe.
Test.obj - 4 error(s), 0 warning(s)