【问题标题】:Why class type object aren't allowed in template parameter? [duplicate]为什么模板参数中不允许使用类类型对象? [复制]
【发布时间】:2014-12-02 12:13:37
【问题描述】:

以下内容不起作用:

// case one:

struct MyClass {
    int x;
};

template <MyClass name>
void foo() {
}

但如果我把它作为参考,它会起作用:

// case two:

struct MyClass {
    int x;
};

template <MyClass &name>
void foo() {
}

我是否需要传递一个 MyClass 的 constant 对象,以便它与类一起使用以防万一?

【问题讨论】:

  • 在这种情况下为什么需要模板?
  • @πάνταῥεῖ:我在问为什么不允许这样做..如果您可以评论它,请因为问题已经结束。就像我知道模板是在编译时推导出来的,但是类对象究竟是一个问题?
  • 副本中的第二个答案很好地描述了为什么不允许使用类类型而不是指针或类引用。

标签: c++ templates


【解决方案1】:

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

也许这就是你想要的?

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 是高度可疑的,我只是在这里举个例子。)

【讨论】:

  • 不,我只想知道如果我使用类对象而不是对它的引用会出现什么问题。它是否与因为模板是在编译时推导出来的?具体如何?
  • @user963241 啊,所以你在这里创建了一个"Function Template"。 "使用类型参数声明函数模板的格式为:template &lt;class identifier&gt; function_declarationtemplate &lt;typename identifier&gt; function_declaration 您选择 identifier,但定义的其余部分必须遵循该格式。template &lt;MyClass name&gt; 不遵循该格式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 2013-09-05
  • 2010-09-17
相关资源
最近更新 更多