c++ - 可变参数模板 : choose the tuple element type that has a proper method

标签 c++ c++11 variadic-templates overload-resolution

我有这样一个类:

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/

相关文章:

c++ - C++11 中的可变参数模板和多重继承

c++ - 错误 : "undefined reference to ' function'"in C++

C++ - 返回 const unique_ptr

c++ - 使用 POD 高效移动类(class)

C++11 lambda 不通过引用获取 const 变量,为什么?

c++ - 操作可变函数模板的函数参数

c++ - 结构化绑定(bind) : loop over deque of tuple

c++ - 在 Mac 上使用 PJSIP 进行回声消除

c++ - 获取指向映射 C++ 中结构的指针

c++ - 如何在编译时初始化静态二维数组