簡體   English   中英

是否可以將參數包擴展為不同的成員函數?

[英]Is it possible to expand a parameter pack into different member functions?

基本上我在想的是:

template<typename... Types>
class Foo
{
    void Bar(Types var) {};...
};

哪個專門這樣:

Foo<S1, S2, S3> foo;

擴展到:

class Foo
{
    void Bar(S1 var){};
    void Bar(S2 var){};
    void Bar(S3 var){};
};

顯然,它在某種程度上沒有意義,但我會很高興看到一些想法。

template<class D, class T>
struct FooHelper {
  void Bar(T var) {
    auto* self=static_cast<D*>(this);
    // here use self instead of this
  };
};
template<typename... Types>
class Foo: FooHelper<Foo,Types>...
{
  template<class D,class T>
  friend struct FooHelper<D,T>;
};

這就是你做你想做的事情。

我們使用CRTP為基類提供對Foo所有內容的訪問。

這是一個很好的C ++ 17方法:

template<typename T>
struct HelpFoo {
  void Bar(T) {}
};

template<typename... Types>
struct Foo : HelpFoo<Types>...
{
    using HelpFoo<Types>::Bar...;
};

您可以使用模板化方法,並使用enable_if啟用包列表中的方法:

#include <type_traits>

template<class... Ts>
struct foo {
    template<class T, std::enable_if_t<
        std::disjunction_v<std::is_same<T, Ts>...>, int> = 0>
   void bar(T);

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM