在全局名称空间中将重载函数声明为模板类的朋友

时间:2018-12-24 03:54:24

标签: c++ class templates namespaces friend

我的问题很简单。我可以使用基本类型在嵌套名称空间中将全局函数的重载函数声明为嵌套名称空间中的模板类的朋友,但是,如果我将函数的定义和声明更改为返回size_t,则会出现C2510和C4430错误。这仅在函数的返回类型中发生。参数列表中的size_t不会产生问题。我也尝试了:: size_t,:: std :: size_t和std :: size_t。似乎没有任何作用。这是怎么回事,为什么?

我正在使用MS Visual Studio 2015

谢谢

已更新:根据评论,我已包含剩余的代码TestingApp.cpp。我还包括了不能解决问题的stddef。关于我收到的特定错误消息,它们是:

C2510   'size_t': left of '::' must be a class/struct/union TestingApp   
pointer.h   41  
C4430   missing type specifier - int assumed. Note: C++ does not support 
default-int TestingApp  pointer.h   41  

不产生编译错误的第41行:

friend int ::fwrite<DATA_TYPE>(const Pointer<DATA_TYPE>& ptr, size_t count, FILE* stream);

确实会产生编译错误的第41行:

friend size_t ::fwrite<DATA_TYPE>(const Pointer<DATA_TYPE>& ptr, size_t count, FILE* stream);

以下两个文件可以编译并正常运行。但是,如果我在前向声明,朋友声明和定义中用int用size_t代替返回类型(无论哪种情况,返回类型都仅将size_t用作函数的第二个参数),则会得到上面指出的错误。

/*******Begin Pointer.h******/

#pragma once
#include <cstdio>

namespace FW{
    namespace Memory {
        template <typename DATA_TYPE> class Pointer;
    }
}

template <typename DATA_TYPE> inline
/* int works, size_t does not work */
int 
/* size_t */
fwrite(const 
FW::Memory::Pointer<DATA_TYPE>& ptr, size_t count, FILE* stream);

namespace FW{
    namespace Memory{

        template <typename DATA_TYPE> class Pointer {

 /*Line 41*/ friend 
             /* int works, size_t does not work */
             int 
             /* size_t */
             ::fwrite<DATA_TYPE>(const Pointer<DATA_TYPE>& ptr, size_t count, FILE* stream);

            public:
                /* Omitted for brevity */
            private:
               DATA_TYPE* m_pCurrent;

        };


    }
}

template <typename DATA_TYPE>
/* int works, size_t does not work */
int 
/* size_t */
fwrite<DATA_TYPE>(const FW::Memory::Pointer<DATA_TYPE>& ptr, size_t count, FILE* stream) {
    return fwrite(ptr.m_pCurrent, sizeof(DATA_TYPE), count, stream);
}

/*******End Pointer.h*******/


/*******Begin TestingApp.cpp******/

// TestingApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cstdio>
#include <cstddef>
#include "..\DB\Pointer.h"

int main()
{
    unsigned long* pData = new unsigned long[100];
    for (size_t i = 0; i < 100; i++) {
        pData[i] = i;
    }
    FW::Memory::Pointer<unsigned long> ptr(pData);
    FILE* pFile = fopen("testFile", "wb");
    if (pFile) {
        fwrite(ptr, 10, pFile);
        fclose(pFile);
    }
    delete[] pData;
    pData = 0;
    return 0;
}

/ *****结束TestingApp.cpp ***** /

0 个答案:

没有答案
相关问题