【问题标题】:shared_ptr template argument invalidshared_ptr 模板参数无效
【发布时间】:2015-10-24 01:54:07
【问题描述】:

我正在尝试让静态方法返回 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

【问题讨论】:

  • 尝试将命名空间 WavFile 限定符添加到 LoadWavFromFile 实现中的返回值,即 shared_ptr<:wavfile>。是的,我知道你说过“使用命名空间 WavFile”。但是由于名称相同,编译器会感到困惑。

标签: c++ shared-ptr


【解决方案1】:

将命名空间名称更改为其他名称。现在它与类名冲突,因为你是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&lt;WafFile::WavFile&gt;

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多