簡體   English   中英

C ++錯誤:專門定義模板類的成員函數的多個定義,但實際上我只定義了一次

[英]C++ error: multiple definition of a member function specialized in template class, but I really defined it only once

問題來自計算機圖形C ++項目,我想在其中計算比例場和3D矢量場的梯度。 我們知道它們的梯度不同:比例場具有3D矢量梯度,而3D向量場具有3x3矩陣梯度。 由於所有其他代碼都相同,因此我正在使用模板來重用代碼。 但是我在專門化成員函數時遇到了一個問題,該成員函數具有用於計算不同數據類型的梯度的不同代碼。 最小化的代碼如下:

//======== Main.cpp ======== 
#include "Render.h"
int main() {}

//======== Render.cpp ======== 
#include "Render.h"

//======== Render.h ======== 
#ifndef __RENDER_H__
#define __RENDER_H__
#include "VolumeGrid.h"
#endif

//======== VolumeGrid.h ======== 
#ifndef __VOLUMEGRID_H__
#define __VOLUMEGRID_H__

#include "Volume.h"

template < typename U >
class _Grid {
public:
    const typename GradType<U>::GType grad(const Vector& x) const;
    U * values = nullptr;
};

template <>
const Vector _Grid<float>::grad(const Vector& x) const {
    return Vector();
}

template <>
const Matrix _Grid<Vector>::grad(const Vector& x) const {
    return Matrix();
}

#endif

//======== Volumn.h ========
#ifndef __VOLUME_H__
#define __VOLUME_H__

#include "Vector.h"
#include "Matrix.h"

template <typename U>
struct GradType {
   typedef int GType;
};

template<>
struct GradType<float> {
   typedef Vector GType;
};

template<>
struct GradType<Vector> {
   typedef Matrix GType;
};

template< typename U >
class Volume {
public:
   typedef U volumeDataType;
   typedef typename GradType<U>::GType volumeGradType;
};

#endif


//======== Vector.h ======== 
#ifndef __VECTOR_H__
#define __VECTOR_H__

class Vector {
public:
    float xyz[3] = { 0,0,0 };
};

#endif

//======== Matrix ========
#ifndef __MATRIX_H__
#define __MATRIX_H__

class Matrix {
  public:
      float m[3][3];
};

#endif

錯誤消息是:

build/Debug/GNU-Linux/Render.o: In function `Vector::Vector()':
/home/CppApplication_1/VolumeGrid.h:19:
multiple definition of `_Grid<float>::grad(Vector const&) const'
build/Debug/GNU-Linux/Main.o:/home/CppApplication_1/VolumeGrid.h:19:
first defined here
build/Debug/GNU-Linux/Render.o: In function
`_Grid<Vector>::grad(Vector const&) const':
/home/CppApplication_1/VolumeGrid.h:24:
multiple definition of `_Grid<Vector>::grad(Vector const&) const'
build/Debug/GNU-Linux/Main.o:/home/CppApplication_1/VolumeGrid.h:24:
first defined here

從代碼中可以看到,分別在VolumeGrid.h中將與不同數據類型相對應的兩個專用grad函數分別定義為Grid<float>類和Grid<Vector>類的成員函數。 但是錯誤消息說它們有多個定義。 該代碼使用g ++ 4.8.4編譯,並在64位ubuntu 14.04上啟用了C ++ 11(在Visual Studio 2015上可以很好地編譯)。 上面的代碼被最小化,因為刪除任何行,例如Main.cpp中的#include "Render.h" ,都會使錯誤消失。 頭文件包含結構和類繼承層次結構不應更改,因為它們在實際項目中使用。 那么,能否請您告訴我grad函數的專業化問題在哪里以及如何解決? 非常感謝你的幫助。

顯式函數模板專門化(沒有模板參數)並不像實際模板那樣隱式inline

將定義移動到* .cpp文件,或將它們標記為inline

如果將它們移動到* .cpp文件,則應在頭文件中聲明它們,例如

template <>
const Vector _Grid<float>::grad(const Vector& x) const;

暫無
暫無

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

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