C ++构造函数模板专业化 [英] C++ constructor template specialization

查看:77
本文介绍了C ++构造函数模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 std :: string 参数创建一个专门的构造函数,但是当我使用字符串参数调用它时,总是使用另一个。 p>

I'm trying to create a specialized constructor for std::string arguments, but the other one is always used when I call it with a string argument.

struct Literal : Expression
{    
    template <typename V>
    Literal(V val)
    {
        value = val;
    }
};

template <>
Literal::Literal(std::string const& val)
{
    value = val.c_str();
}

两者都定义在类内还是外部都没关系类,或者像在发布的示例中一样,仅在类之外定义了专业化:当使用 std :: string 进行调用时,赋值 value = val 给出了编译器错误。

It doesn't matter if both are defined inside the class, both outside the class, or like in the posted example only the specialization is defined outside the class: When called with std::string, the assignment value = val gives a compiler error.

如何正确地为 std :: string

推荐答案

您不知道。

您应该重载构造函数 Literal(const std :: string&),您可以在 struct 声明。

You should overload the constructor: Literal(const std::string&), which you can do in the struct declaration.

编译器总是尝试在非模板重载之前匹配非模板重载。

The compiler always tries to match non-template overloads before template ones.

这篇关于C ++构造函数模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆