c++ - 在带有可变参数模板的基于模板的类中进行完善转发?

标签 c++ templates variadic-templates

我尝试实现模板基类。它采用字符串和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

任何帮助,将不胜感激。

最佳答案

temp<int>具有成员函数main_fn(const std::string& a),因为Args...中没有其他temp<int>

如果要对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;

}

关于c++ - 在带有可变参数模板的基于模板的类中进行完善转发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61089835/

相关文章:

c++ - gtkmm/c++ 第一个 hello world 示例泄漏内存

c++ - 使用 C++ 进行 iPhone Quartz 2d 开发?

c++ - unique_ptr 的 remove_pointer

c++ - 带有可变参数模板的奇怪的重复模板模式 (C++)

c++ - 在 C++ 中处理许多进程的中央数据缓冲区

c++ - 重定向到文件后,使用 cout 或 cerr 输出到控制台

c++ - 为什么 std::less 是类模板?

templates - 速度模板包括主模板

c++ - 混合 void_t 和可变参数模板?

c++ - 在 C++ 中构造一个 'is_template_instantiable' 类型特征