【问题标题】:Which foo template will be instantiated?哪个 foo 模板将被实例化?
【发布时间】:2014-06-03 02:28:05
【问题描述】:

鉴于此代码:

#include <type_traits>
template<char ...Cs>
auto foo() -> typename std::enable_if<(sizeof...(Cs) > 1)>::type{
}

template<char C>
void foo() {
}

int main(){
    foo<'s'>();
}

我有上面的 c++ 程序,我只是想知道,根据标准中规定的规则,两个“foo”模板中的哪一个将被实例化用于 main 中的“foo”调用。

【问题讨论】:

  • 它不打印任何东西...?
  • 你试过运行它吗?此外,没有明显的print 功能......
  • 这是漫长的一天。我的意思是应该调用哪个 foo。
  • 没有。因为你什么都没打电话。
  • 你应该看看 SFINAE。当sizeof...(Cs) &lt; 2 与您的情况一样,第一个模板被禁用。

标签: c++ templates variadic-templates sfinae template-argument-deduction


【解决方案1】:

您可以为每一个添加打印以查找:

template<char ...Cs>
auto foo() -> typename std::enable_if<(sizeof...(Cs) > 1)>::type{
    cout << "1" << endl;
}
template<char C>
void foo() {
    cout << "2" << endl;
}
void EnableIfWithSizeof(){
    foo<'s'>();
}

int main() {
EnableIfWithSizeof();
return 0;
}

结果输出为2

【讨论】:

  • 是的,我知道。问题是标准中的哪条规则规定了这一点。
  • 是的,我正在努力解决这个问题。
  • 这看起来类似于cppreference example。由于sizeof...(Cs)&gt;1 为假,::type 存在替换失败,因此不考虑该行。
猜你喜欢
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多