我只是想分享解決我尋求的一般問題。 Barry對上述具體問題的解決方案使之成爲可能:
#include <iostream>
#include <utility>
#include <tuple>
template <template <std::size_t, typename> class Check, typename F, size_t... Js, typename Tuple>
void screenArguments (std::index_sequence<>, std::index_sequence<Js...>, const Tuple& tuple) {
F()(std::get<Js>(tuple)...);
}
template <template <std::size_t, typename> class Check, typename F, std::size_t I, size_t... Is, size_t... Js, typename Tuple>
void screenArguments (std::index_sequence<I, Is...>, std::index_sequence<Js...>, const Tuple& tuple) {
if (Check<I, Tuple>::execute(tuple))
screenArguments<Check, F>(std::index_sequence<Is...>{}, std::index_sequence<Js..., I>{}, tuple);
else
screenArguments<Check, F>(std::index_sequence<Is...>{}, std::index_sequence<Js...>{}, tuple);
}
template <template <std::size_t, typename> class Check, typename F, typename Tuple, std::size_t N = std::tuple_size<Tuple>::value>
void passCertainArguments (const Tuple& tuple) {
screenArguments<Check, F> (std::make_index_sequence<N>{}, std::index_sequence<>{}, tuple);
}
// Testing
#include <typeinfo>
template <typename... Args>
void foo (Args&&...) {
std::cout << sizeof...(Args) << " elements passed into foo.\n";
}
struct Foo {
template <typename... Args>
void operator()(Args&&... args) {
foo(std::forward<Args>(args)...);
}
};
template <typename... Args>
void bar (Args&&...) {
std::cout << sizeof...(Args) << " elements passed into bar.\n";
}
struct Bar {
template <typename... Args>
void operator()(Args&&... args) {
bar(std::forward<Args>(args)...);
}
};
template <std::size_t N, typename Tuple>
struct CheckArguments {
static bool execute (const Tuple& tuple) {
return std::get<N>(tuple) != std::get<N+1>(tuple);
}
};
struct NullObject {};
template <std::size_t N, typename Tuple>
struct CheckNotNullObject {
static bool execute (const Tuple& tuple) {
return typeid(std::get<N>(tuple)) != typeid(NullObject);
}
};
template <typename F, typename... Args>
void executeWithoutNullObject (Args&&... args) {
passCertainArguments<CheckNotNullObject, F> (std::forward_as_tuple(args...));
}
template <typename F, typename... Args>
void executeRemoveConsecutiveRepeatElements (Args&&... args) {
const auto tuple = std::forward_as_tuple(args...);
passCertainArguments<CheckArguments, F, decltype(tuple), sizeof...(Args) - 1> (tuple);
}
int main() {
executeWithoutNullObject<Foo> (3, 5, 'a', true, NullObject{}, 'b', 5.8, NullObject{}, NullObject{}, '!', 2);
// 8 elements passed into foo. (the 3 NullObjects are removed)
executeRemoveConsecutiveRepeatElements<Bar> (2, 1.5, 'a', 'a', true, 5, 5, false);
// 5 elements passed into bar. (the first 'a', the first 5, and 'false' removed)
}
您不能與* ternary *表達式關聯。爲什麼不使用'if'語句?或者在三元表達式中調用'f'函數,而不是在'f'調用中使用三元表達式。 –
如果你可以通過編譯類型替換你的'std :: set'內容,你可以這樣做:[Demo](https://ideone.com/ZBF92c) – Jarod42
@ Jarod42對不起,我簡化了這個問題,更新了問題。我不確定你的技術是否仍然適用。 – prestokeys