【问题标题】:Prefect Forwarding in a template based class with variadic templates?在具有可变参数模板的基于模板的类中完美转发?
【发布时间】:2020-04-07 21:40:33
【问题描述】:

我尝试实现一个模板基类。它采用一个字符串和 n 个参数,并基于字符串将所有给定的参数传递给使用完美转发的某个函数。 我为此编写了一个示例代码。

template <typename T, typename ... Args>
class temp {
    public:
        temp(){};
        ~temp(){};
        T main_fn(const std::string& a, Args&& ... args){
            if(a == "add"){
                return add(std::forward<Args>(args)...);
            }
            else if(a == "sub"){
                return sub(std::forward<Args>(args)...);
            }
            else{
                std::cout << "abc" << std::endl;
            }     
        }  
};

int main(){

  std::cout << std::endl;
  temp<int>* temp_obj = new temp<int>();
  const std::string fn = "add";
  int result = temp_obj->main_fn(fn, 1,2,3);
  std::cout << result << std::endl;

}

当我尝试编译此代码时,出现以下错误。

 In function 'int main()':
70:43: error: no matching function for call to 'temp<int>::main_fn(const string&, int, int, int)'
70:43: note: candidate is:
40:11: note: T temp<T, Args>::main_fn(const string&, Args&& ...) [with T = int; Args = {}; std::string = std::basic_string<char>]
40:11: note:   candidate expects 1 argument, 4 provided

任何帮助将不胜感激。

【问题讨论】:

    标签: c++ templates variadic-templates


    【解决方案1】:

    temp&lt;int&gt; 具有成员函数main_fn(const std::string&amp; a),因为在temp&lt;int&gt; 中没有进一步的Args...

    如果你想参数化T 上的类,但更多Args... 上的方法,那么你可以这样写:

    #include <iostream>
    #include <string>
    template <typename T>
    class temp {
        public:
            temp(){};
            ~temp(){};
            template <typename ... Args>
            T main_fn(const std::string& a, Args&& ... args){
                return 42;
            }  
    };
    
    int main(){
    
      std::cout << std::endl;
      temp<int>* temp_obj = new temp<int>();
      const std::string fn = "add";
      int result = temp_obj->main_fn(fn, 1,2,3);
      std::cout << result << std::endl;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 2013-01-06
      • 2012-01-06
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多