【问题标题】:Template instantiation refused with function-local classes [duplicate]函数本地类拒绝模板实例化[重复]
【发布时间】:2010-07-30 09:38:40
【问题描述】:

可能重复:
How to use local classes with templates?

g++ 4.4 拒绝编译对将函数本地类作为模板参数的模板函数的调用。像这样:

// Given this:
template <typename C>
int f(const C& c) {
  return c.g();
}

// This compiles fine:
struct C1 {
    int g() const { return 42; }
};

int h1() {
    return f(C1());
}

// But this doesn't:
int h2() {
    struct C2 {
        int g() const { return 42; }
    };
    return f(C2()); // error: no matching function for call to "f(h2()::C2)"
}

// Nor does this:
int h3() {
    struct C3 {
        int g() const { return 42; }
    };
    return f<C3>(C3()); // same error
}

什么给了?我该如何进行这项工作? (在修剪 this 的实际程序中,“h”是一个成员函数,“C”必须是一个嵌套类,以便它隐含地成为“h”是其成员的类的朋友。)

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    C++0x 将移除这个不受欢迎的限制。

    现在,您可以让 C i 成为一个适当的嵌套类(在 h 的类内,而不是在 h 内)。

    【讨论】:

    • 感谢您的解决方法。很不幸,因为“C”只用在那个地方,但至少我不必把不应该公开的事情公开。
    【解决方案2】:

    本地类可能不是模板参数。

    C++ can local class reference be passed to a function?

    【讨论】:

    【解决方案3】:

    模板参数必须有外部链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      相关资源
      最近更新 更多