c++ - 使用模板将任何类型的参数传递给 c++ 中的函数

标签 c++ templates

我想将任何类型的参数传递给我的函数 func1()。 所以这是我的代码: 我的类.h :

public:
   myclass();
   template<typename T> void func1(T object);

我的类.cpp:

template<typename T> 
void myclass::func1(T object)
{
    return;
}

ma​​in.cpp :

int a=0;
myclass::func1<int>(a);

但是我得到了这个错误:

error: cannot call member function 'void myclass::func1(T) [with T = int]' without object

我的错误在哪里?

最佳答案

您不能简单地将模板函数中的声明和定义分开。对于模板函数,最简单的做法是在头文件中的函数声明中提供代码体。

如果您想在没有类对象的情况下调用函数,请将静态添加到函数签名中。

标题.hpp

#include <iostream>

class test_class{
public:
     template<typename T> static void member_function(T t){
        std::cout << "Argument: " << t << std::endl;
    }

};

主要.cpp

#include <iostream>

#include "header.hpp"

int main(int argc, char ** argv){

    test_class::member_function(1);
    test_class::member_function("hello");
}

关于c++ - 使用模板将任何类型的参数传递给 c++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281602/

相关文章:

c++ - 从 C++ 调用 Haskell

c++ - 为什么在 C++14 中不推荐使用 std::shuffle 方法?

c++ - 有人可以解释使用递归模板生成整数序列吗?

java - 在 Android/Java 中使用 ViewHolder 的通用类

c++ - 用模板替换复合虚拟

python - 解析非二进制大文件(Python 或 C++)

c++ - 强制在某个静态字段之前初始化全局变量

c++ - 崩溃 : this may be due to a corruption of the heap

html - 如何在 Bootstrap 中制作这样的表格?

xslt - 调用同一个 xsl :template for different node names of the same complex type