簡體   English   中英

重載可變參數模板成員函數和可變參數模板函數

[英]Overloading variadic-templated member function and variadic-templated functions

有沒有簡單的方法可以用通用函數重載可變參數模板化函數,如此處的構造函數所示, c ++可變參數模板構造函數和通用構造函數 (c ++ 11-c ++ 14)

#include <iostream>

struct S {};

class C
{
  public:
  void fun(S const&) { std::cout << " fun(S const& ) " << std::endl; } // 1

  template<typename ... T>
  void fun(T&&...) { std::cout << " fun(T&&...) " << std::endl; } // 2
};

int main ()
{
    S s{};
    C c{};

    c.fun(s);
    c.fun(5); // call 1 - ?
}

我想做c.fun(5)來調用非可變模板版本。 對於使用std::enable_ifstd::is_constructible構造函數,顯示了類似的解決方案。 我需要重載需求

我只是做一個變通辦法,不是很優雅

#include <iostream>
#include <type_traits>

struct S {};

class C
{
    class helper
    {
    public:
      helper(S const&) { std::cout << " fun(S const& ) " << std::endl; }

      template<typename ... T, typename = std::enable_if_t<!std::is_constructible<helper, T&&...>::value> >
      helper(T&&...) { std::cout << " fun(T&&...) " << std::endl; }
    };

  public:

  template<typename ... T>
  void fun(T&&... args) { helper { std::forward<T>(args)... }; }


};


int main ()
{
    S s{};
    C c{};

    c.fun(s);
    c.fun(5);

}

暫無
暫無

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

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