我试图根据模板参数用不同的代码填充我的类,但出现编译错误。我的代码是这样的:
#include <iostream>
#include <string>
struct EmptyType { };
template<class arg1=EmptyType, class arg2=EmptyType, class arg3=EmptyType>
class my_class
{
my_class(){
std::cout << 3 << std::endl;
}
// FILL_MY_CLASS_DEFINE(3)
};
template<class arg1, class arg2>
class my_class<arg1,arg2,EmptyType>
{
my_class(){
std::cout << 2 << std::endl;
}
// FILL_MY_CLASS_DEFINE(2)
};
template<class arg1>
class my_class<arg1,EmptyType,EmptyType>
{
my_class(){
std::cout << 1 << std::endl;
}
};
template<>
class my_class<EmptyType,EmptyType,EmptyType>
{
// FILL_MY_CLASS_DEFINE(0)
};
int main(int argc, const char *argv[])
{
my_class<std::string, double, int> a;
my_class<std::string, int> b;
my_class<void> c;
//my_class d;
return 0;
}
我收到很多错误:
prog.cpp: In function ‘int main(int, const char**)’:
prog.cpp:9: error: ‘my_class<arg1, arg2, arg3>::my_class() [with arg1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, arg2 = double, arg3 = int]’ is private
prog.cpp:38: error: within this context
prog.cpp:17: error: ‘my_class<arg1, arg2, EmptyType>::my_class() [with arg1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, arg2 = int]’ is private
prog.cpp:39: error: within this context
prog.cpp:25: error: ‘my_class<arg1, EmptyType, EmptyType>::my_class() [with arg1 = void]’ is private
prog.cpp:40: error: within this context
现场代码在这里。所以我想知道:当用 C++03 模拟可变参数模板时,一个类中是否可以有不同的代码?