我有这样一个类:
template <typename... Types>
class Evaluator
{
public:
template <typename... Types>
Evaluator(Types... args)
{
list = std::make_tuple(args...);
}
template <typename T>
bool Evaluate(const T& input)
{
// based on a specific input type T, here I want to call
// Evaluate(input) for a specific element in the tuple. i.e. the
// element that has method Evaluate, for which Evaluate(input) compiles
return std::get<0>(list).Evaluate(input);
}
private:
std::tuple<Types...> list;
};
更新 对于没有正确“Evaluate(input) -> bool”函数的实例,该函数可能会返回 false,并且会针对所有与 bool 结果匹配的情况进行评估 ||
最佳答案
像这样:
// Unspecialized form, when the current element doesn't match. Tries the next one.
template <typename Tuple, int I, typename Argument, typename = void>
struct CallEvaluate : CallEvaluate<Tuple, I+1, Argument> {};
// Termination case, when the end of the tuple was reached. Has no operator () and will
// cause a compilation error.
template <typename Tuple, typename Argument>
struct CallEvaluate<Tuple, std::tuple_size<I>::value, Argument> {}; // no type fits
// Termination case, when the call std::get<I>(list).Evaluate(input) is valid.
template <typename Tuple, int I, typename Argument>
struct CallEvaluate<Tuple, I, Argument,
decltype(void(
std::declval<typename std::tuple_element<Tuple, I>::type>()
.Evaluate(std::declval<const Argument&>())))> {
bool operator ()(const Tuple& list, const Argument& input) const {
return std::get<I>(list).Evaluate(input);
}
};
// Use:
CallEvaluate<decltype(list), 0, T>()(list, input);
关于c++ - 可变参数模板 : choose the tuple element type that has a proper method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18468106/