编辑:好的,您的问题的标题似乎具有误导性
"我想要一个类,它的构造函数中有两个参数。第一个可以是 int、double 或 float,所以,第二个总是字符串字面量“我的字符串”,所以我猜是 const char * const 。”
看起来你正在努力实现:
template<typename T>
class Foo
{
public:
Foo(T t, const char* s) : first(t), second(s)
{
// do something
}
private:
T first;
const char* second;
};
这适用于任何类型,对于第一个参数:int、float、double 等等。
现在如果你真的想限制第一个参数的类型只能是int、float或double;你可以想出一些更精细的东西,比如
template<typename T>
struct RestrictType;
template<>
struct RestrictType<int>
{
typedef int Type;
};
template<>
struct RestrictType<float>
{
typedef float Type;
};
template<>
struct RestrictType<double>
{
typedef double Type;
};
template<typename T>
class Foo
{
typedef typename RestrictType<T>::Type FirstType;
public:
Foo(FirstType t, const char* s) : first(t), second(s)
{
// do something
}
private:
FirstType first;
const char* second;
};
int main()
{
Foo<int> f1(0, "can");
Foo<float> f2(1, "i");
Foo<double> f3(1, "have");
//Foo<char> f4(0, "a pony?");
}
如果您删除最后一行的注释,您实际上会得到一个编译器错误。
C++2003 不允许使用字符串字面量
ISO/IEC 14882-2003 §14.1:
14.1 模板参数
非类型模板参数应具有以下类型之一(可选 cv 限定):
——整数或枚举类型,
——指向对象的指针或指向函数的指针,
——对对象的引用或对函数的引用,
——指向成员的指针。
ISO/IEC 14882-2003 §14.3.2:
14.3.2 模板非类型参数
非类型、非模板模板参数的模板参数应为以下之一:
——整数或枚举类型的整数常量表达式;或
——非类型模板参数的名称;或
— 具有外部链接的对象或函数的地址,包括函数模板和函数模板 ID,但不包括非静态类成员,表示为 & id 表达式,如果名称引用函数或数组,则 & 是可选的,或者如果相应的模板参数是参考;或
——指向成员的指针,如 5.3.1 所述。
[注意:字符串文字 (2.13.4) 不满足任何这些类别的要求,因此不是可接受的模板参数。
[示例:
template<class T, char* p> class X {
//...
X();
X(const char* q) { /* ... */ }
};
X<int,"Studebaker"> x1; //error: string literal as template-argument
char p[] = "Vivisectionist";
X<int,p> x2; //OK
——结束示例]——结束注释]
而且看起来它在即将到来的 C++0X 中不会改变,see the current draft 14.4.2 Template non-type arguments。