仅在可变参数模板类中调用现有函数

问题描述 投票:1回答:1

我有一个可变参数化的模板类,我想仅当模板类具有该函数时才调用该函数。

到目前为止我所拥有的如下。

#include <cstdio>
#include <type_traits>

template <typename>
constexpr std::false_type hasFooHelper(long);

template <typename T>
constexpr auto hasFooHelper(int)
   -> decltype( std::declval<T>().foo(), std::true_type{} );

template <typename T>
using has_foo = decltype( hasFooHelper<T>(0) );

class WithFoo
{
public:
    void foo()
    {
        printf("%s\n", __func__);
    }
};

template <class... T>
class myclass
{
public:
    void invokeFoo()
    {
        if constexpr((has_foo<T>() && ...))
        {
            (T().foo(), ...);
        }
    } 
};

int main()
{
    myclass<WithFoo> a;
    myclass<int> b;
    myclass<WithFoo, int> c;

    a.invokeFoo(); // Invokes WithFoo::foo()
    b.invokeFoo(); // Do nothing
    c.invokeFoo(); // Do nothing, how to make this invoke WithFoo::foo()?
    return 0;
}

myclass<WithFoo>myclass<int>可以正常使用,但myclass<WithFoo, int>则不起作用。

如何使myclass<WithFoo, int>也调用WithFoo::foo()

c++ c++17 variadic-templates
1个回答
1
投票

此:

if constexpr((has_foo<T>() && ...))
{
    (T().foo(), ...);
}
© www.soinside.com 2019 - 2024. All rights reserved.