【问题标题】:Ambiguous template instantiation模棱两可的模板实例化
【发布时间】:2018-05-10 18:59:30
【问题描述】:

有人可以解释这里的歧义吗?

template <typename...> struct thing;

template <typename... Rest>
struct thing<int&, Rest&...> {
    thing(int&, Rest&...) { }
};

template <typename First, typename... Rest>
struct thing<First&, Rest&...> {
    thing(First&, Rest&...) { }
};

int main() {
    int myint;
    char mychar;
    thing<int&, char&> t(myint, mychar);
}

【问题讨论】:

  • 嗯,你指的是哪个?需要 1 + 其他 args 的那个,还是需要 2 + 其他 args 的那个?
  • 第一个专业不是比第二个专业吗?它应该自动取第一个,对吧?
  • 这可能是编译器错误。
  • 您可以使用template &lt;typename ... Ts&gt; struct thing&lt;Ts&amp;...&gt; : thing_for_ref&lt;Ts...&gt; {}(然后专门化thing_for_ref)作为解决方法。
  • 使用 SFINAE 的工作解决方法:wandbox.org/permlink/cPGy0K4I5BR2EWIm

标签: c++ c++11 templates ambiguity


【解决方案1】:

如果你专注于 int 而不是 int&amp; 它可以工作

template <typename...> struct thing;

template <typename... Rest>
struct thing<int, Rest...> {
    thing(int&, Rest&...) { }
};

template <typename First, typename... Rest>
struct thing<First, Rest...> {
    thing(First&, Rest&...) { }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2015-01-12
    相关资源
    最近更新 更多