相关疑难解决方法(0)

在.CPP文件中存储C++模板函数定义

我有一些模板代码,我宁愿存储在CPP文件中而不是标题中的内联.我知道只要您知道将使用哪些模板类型,就可以完成此操作.例如:

.h文件

class foo
{
public:
    template <typename T>
    void do(const T& t);
};
Run Code Online (Sandbox Code Playgroud)

.cpp文件

template <typename T>
void foo::do(const T& t)
{
    // Do something with t
}

template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);
Run Code Online (Sandbox Code Playgroud)

注意最后两行--foo :: do模板函数仅用于int和std :: strings,因此这些定义意味着应用程序将链接.

我的问题是 - 这是一个讨厌的黑客还是会与其他编译器/链接器一起使用?我目前只在VS2008上使用此代码,但是想要移植到其他环境.

c++ templates

484
推荐指数
8
解决办法
31万
查看次数

模板化静态成员函数在C++中

我编写了一个简单的测试程序,试图学习如何在C++中使用模板静态成员函数.代码编译,但不能正常工作(打印出一些垃圾).我想我正在使用正确的语法.我已经读过这个或者这个和其他一些东西,但仍然不知道我做错了什么.代码如下:

#include <iostream>
using namespace std;

class Util {
public:
    Util();
    virtual ~Util();

    template <typename T> static void printTab(T tab[]);
};

template <typename T>
void Util::printTab(T tab[]) {
    for (unsigned int i=0; i<sizeof(tab)/sizeof(tab[0]); i++) {
        cout << tab[0] << " ";
    }
    cout << endl;
}

int main() {

    float tabFloat[5] {1, 2, 3, 4, 5};
    unsigned char tabChar[3] {1, 2, 3};

    Util::printTab(tabFloat);
    Util::printTab(tabChar);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

任何提示赞赏.

c++ templates static-methods

4
推荐指数
1
解决办法
216
查看次数

c ++中的模板成员函数

我在c ++中有泛型问题.我有两个Matrix.h和Matrix.cpp文件.这是文件:

#pragma once
template<class T>
class Matrix
{
    public:
        static T** addSub(int size,T** firstMatrix,T** secondMatrix,int operation);
}
Run Code Online (Sandbox Code Playgroud)

和Matrix.cpp

#include "Martix.h"
template<class T>
static T** Matrix<T>::addSub( int n,T **firstMatrix,T **secondMatrix,int operation)
{
    //variable for saving result operation
    T **result = new T*[n];

    //create result matrix
    for( int i=0;i<n;i++)
        result[i] = new T[n];

    //calculate result
    for( int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            result[i][j] = 
            (operation == 1) ? firstMatrix[i][j] + secondMatrix[i][j]:
                                firstMatrix[i][j] - secondMatrix[i][j];

    return result;
}
Run Code Online (Sandbox Code Playgroud)

当我运行这些时,我收到以下错误:

Error   1   error LNK2019: unresolved …
Run Code Online (Sandbox Code Playgroud)

c++ templates

3
推荐指数
1
解决办法
215
查看次数

标签 统计

c++ ×3

templates ×3

static-methods ×1