为什么sizeof ...无法与此别名模板一起使用?

时间:2018-07-14 07:57:56

标签: c++ templates visual-c++ visual-studio-2017 sfinae

我想将可变参数函数限制为一定数量的输入-例如两个。为此,这在我的环境(VS2017,C ++ 17)中可以正常工作:

#include <type_traits>

template<typename... T> 
auto f(T...) -> typename std::enable_if<sizeof...(T) == 2>::type {
    // no-op
}

int main() {
    // f(1); // should fail
    f(1,2);
    // f(1,2,3); // should fail
}

但是,如果我引入别名模板,则不会。

#include <type_traits>

template<typename... T> 
using two_params = typename std::enable_if<sizeof...(T) == 2>::type; 


template<typename... T> 
auto f(T...) -> two_params<T...> { // failed to specialize alias template

}

int main() {
    // f(1); // should fail
    f(1,2);
    // f(1,2,3); // should fail
}

有趣的是,如果将条件更改为1 实际所需的输入数量,则替换成功。

// This works, except that it permits a single argument even when it shouldn't.
// Both conditions ||'d together seems to be needed in the general case.
template<typename... T> 
using two_params = typename std::enable_if<sizeof...(T) == 1 || sizeof...(T) == 2>::type; 

似乎f(1,2)生成sizeof...(T)的两个值。到底是怎么回事?

我看过的一些参考文献:

1 个答案:

答案 0 :(得分:1)

来自微软的乔纳森·埃米特(Jonathan Emmett)仅confirmed就是编译器错误:

  

感谢这份报告。我可以确认这是一个编译器错误,   别名模板和包扩展。我们目前正在研究   别名专业化的主要修复程序,这项工作是   目前预计将包含在VS 2017 15.9版本中。我可以   还请确认此错误已在返工过程中得到修复。

相关问题