krs*_*rsi 6 c++ enable-if variadic-templates
这两个非可变函数模板可以编译:
template <typename T, typename U>
typename std::enable_if<std::is_same<U, int>::value, void>::
type testFunction(T a, U b) {
std::cout << "b is integer\n";
}
template <typename T, typename U>
typename std::enable_if<std::is_same<U, float>::value, void>::
type testFunction(T a, U b) {
std::cout << "b is float\n";
}
Run Code Online (Sandbox Code Playgroud)
但是,类似的可变参数模板不能编译:
template <typename T, typename... U>
typename std::enable_if<std::is_same<U, int>::value, void>::
type testFunction(T a, U... bs) {
std::cout << "bs are integers\n";
}
template <typename T, typename... U>
typename std::enable_if<std::is_same<U, float>::value, void>::
type testFunction(T a, U... bs) {
std::cout << "bs are floats\n";
}
Run Code Online (Sandbox Code Playgroud)
也许我正在尝试做一些无法做到的事情.我知道使用初始化列表可以实现类似的功能,但我想避免使用初始化列表参数所需的大括号.
是.你可以在C++ 17中使用fold表达式:
template <typename T, typename... U>
typename std::enable_if<(std::is_same<U, float>::value && ...), void>::
type testFunction(T a, U... bs) {
std::cout << "bs are floats\n";
}
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,您可以重新实现std::conjunction:
template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), conjunction<Bn...>, B1> {};
Run Code Online (Sandbox Code Playgroud)
template <typename T, typename... U>
typename std::enable_if<
std::conjunction_v<std::is_same<U, float>...>,
void
>::type testFunction(T a, U... bs) {
std::cout << "bs are floats\n";
}
Run Code Online (Sandbox Code Playgroud)