【问题标题】:Why do I get this error? template argument '' is invalid为什么我会收到此错误?模板参数“”无效
【发布时间】:2022-01-18 04:29:00
【问题描述】:

我正在尝试使用std::string 作为typename Tconst char 创建一个模板:

test.cpp

template <typename T, const char N>
class MyClass
{
public:
    static const char Get()
    {
        return N;
    }
};

template <>
class MyClass<std::string, const char N>
{
public:
    static const char Get()
    { 
        return n;
    }
};

测试.h

int main(){
    const char c = 's';
    std:: cout << MyClass<std::string, c>::Get() << std::endl;
};

但我收到以下错误:

template argument 2 is invalid
class MyClass<std::string, const char N>

【问题讨论】:

  • 为什么main().h文件中,而类在.cpp文件中?您的文件扩展名向后。无论如何,如果您将字符文字直接传递给模板,您是否会遇到相同的错误,例如:MyClass&lt;std::string, 's'&gt;::Get()?另外,您对Get() 的专业化正在返回未定义的n,您的意思是不是N
  • 由于您只是部分专门化了类模板,它应该是template&lt;const char N&gt; class MyClass&lt;std::string, N&gt;
  • 我建议你把你的问题改成Why do I get this error "template argument 2 is invalid" in c++? When trying to create a template with std::string我这边的诚实问题,你的问题中的“”是什么意思?我不熟悉那个符号。
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: c++ templates


【解决方案1】:

const 作为非类型模板参数的顶级修饰符是多余的。 Get 返回类型也是如此。你还有一个小错字,n 应该是N。并且你用 cpp 内容切换了 header 内容。

但主要问题是您如何专业化您的模板。你想要的是部分专业化。这是更正的代码:

template <typename T, char N>
class MyClass
{
public:
    static char Get() { return N; }
};

template <char N>
class MyClass<std::string, N>
{
public:
    static char Get() {  return N; }
};

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2018-06-22
    • 2016-01-01
    • 2017-11-30
    相关资源
    最近更新 更多