c++ - shared_ptr 模板参数无效

标签 c++ shared-ptr

我试图让一个静态方法返回一个shared_ptr。

它没有编译并且给出模板参数 1 无效。

我不明白这是为什么。

此外,堆栈溢出表明我的帖子主要是代码,我应该添加更多细节。我不知道为什么会这样,因为简洁不会伤害任何人。我的问题很明确,并且可以很容易地详细说明。

编译器错误

src/WavFile.cpp:7:24: error: template argument 1 is invalid
 std::shared_ptr<WavFile> WavFile::LoadWavFromFile(std::string filename)

WavFile.cpp

#include "WavFile.h"
#include "LogStream.h"
#include "assert.h"

using namespace WavFile;

std::shared_ptr<WavFile> WavFile::LoadWavFromFile(std::string filename)
{
    ifstream infile;        
    infile.open( filname, ios::binary | ios::in );  
}

WavFile.h

#pragma once

#ifndef __WAVFILE_H_
#define __WAVFILE_H_

#include <fstream>
#include <vector>
#include <memory>

namespace WavFile
{
    class WavFile;
}

class WavFile::WavFile
{

    public: 

        typedef std::vector<unsigned char> PCMData8_t;
        typedef std::vector<unsigned short int> PCMData16_t;

        struct WavFileHeader {


            unsigned int num_channels;
            unsigned int sample_rate;
            unsigned int bits_per_sample;
        };

        static std::shared_ptr<WavFile> LoadWavFromFile(std::string filename);

    private:
        WavFile(void);  

    private:                
        WavFileHeader m_header;
        PCMData16_t m_data16;
        PCMData8_t m_data8;
};

#endif

最佳答案

将命名空间名称更改为其他名称。现在它与类(class)名称冲突,因为你是 using namespace WavFile; 。说明错误的简单示例:

#include <iostream>
#include <memory>

namespace X // changing this to Y makes the code compilable
{
    class X{};
}

using namespace X;     // now both class X and namespace X are visible
std::shared_ptr<X> v() // the compiler is confused here, which X are you referring to?
{
    return {};
}

int main() {}

如果您坚持将命名空间命名为类,请删除 using namespace X;并限定类型,std::shared_ptr<WafFile::WavFile> .

关于c++ - shared_ptr 模板参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313723/

相关文章:

c++ - 在 C++ 中解析本地时间

c++ - 将 shared_ptr 传递给 std::fstream * 编辑

c++ - 什么时候在 Qt 中删除小部件(QVBoxLayout 类)?

c++ - vector 检查不起作用

c++ - 将位图数据加载到 OpenGL 纹理中时出现问题

c++ - 子字符串丢失字符串输入

c++ - 原始套接字的 udp 数据包碎片

c++ - 对象在列表中添加和删除自身

c++ - 了解 Scott Meyers 的第三个 std::weak_ptr 示例

c++ - 使用shared_ptr时无法解析的外部符号