如果只有一个类,如何调用特定方法?

Rin*_*dov 1 c++ templates template-meta-programming c++14 c++17

我有一组不同类的对象.我想迭代元组并仅在这些类有一个时才调用某个方法.

例如(伪代码):

struct A {  int get( ) { return 5; }; };
struct B { }; 
struct C {  int get( ) { return 10; }; };
int i = 0;
tuple<A, B, C> t;
for ( auto t_element : t ) 
{
    if constexpr ( has_get_method( decltype(t_element) ) )
    {
        i += t_element.get( );
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经知道如何迭代元组并检查一个类是否有一些使用sfinae的方法但是如何跳过没有所需方法的对象?

sky*_*ack 5

只需写一个sfinae'd函数和一个catchall,以防前一个失败.你不必使用if constexpr它,你不能在C++ 14中实际使用它(这就是你标记问题的方式).
这是一个最小的工作示例:

#include <tuple>
#include <iostream>

auto value(...) { return 0; }

template <typename T>
auto value(T &t) -> decltype(t.get()) {
    return t.get();
}

struct A { int get() { return 5; }; };
struct B {}; 
struct C { int get() { return 10; }; };

int main() {
   int i = 0;

   std::tuple<A, B, C> t;

   i += value(std::get<0>(t));
   i += value(std::get<1>(t));
   i += value(std::get<2>(t));

   std::cout << i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

wandbox上查看并运行.

如果您要使用任何参数进行测试,可以使用std::forwardas:

template <typename T, typename... Args>
auto value(T &t, Args&&... args)
-> decltype(t.get(std::forward<Args>(args)...))
{ return t.get(std::forward<Args>(args)...); }
Run Code Online (Sandbox Code Playgroud)

然后将其调用为:

i += value(std::get<0>(t), params);
Run Code Online (Sandbox Code Playgroud)