为什么模板参数中不允许类类型对象?

Why class type object aren't allowed in template parameter?

本文关键字:类型 对象 不允许 参数 为什么      更新时间:2023-10-16

以下内容不起作用:

// case one:
struct MyClass {
    int x;
};
template <MyClass name>
void foo() {
}

但是如果我把它作为一个参考,它可以工作:

// case two:
struct MyClass {
    int x;
};
template <MyClass &name>
void foo() {
}

我是否需要传递 MyClass 的常量对象才能在万一的情况下与类一起使用?

看起来您正在尝试专门化模板?

也许这就是你想要的?

template <typename T>
void foo(const T& param){
    cout << reinterpret_cast<const int&>(param) << endl;
}
template <>
void foo(const MyClass& param) {
    cout << param.x << endl;
}
int main() {
    MyClass bar = {13};
    foo(42L); // Outputs 42
    foo(bar); // Outputs 13
    return 0;
}

(请注意,reinterpret_cast是高度可疑的,我只是在这里使用它作为一个例子。