c++ - 将 C++ 类更改为模板

标签 c++ class templates

更新:感谢您的所有回复,我确实通知了我的教授,他解决了他这边的问题。再次感谢您的帮助!!

我把我的类变成了一个模板,并尝试运行下面的代码,只得到三个错误。

排序器.h

#pragma once

#ifndef SORT_THINGS
#define SORT_THINGS

#include <utility>
template <typename T>
class sorter {
    public:
        sorter(T a,T b,T c): _a{a}, _b{b}, _c{c} {
            using std::swap;

            if (_a > _b) { swap (_a, _b); }
            if (_b > _c) { swap (_b, _c); }
            if (_a > _b) { swap (_a, _b); }
        }

        const T& a() const { return _a; }
        const T& b() const { return _b; }
        const T& c() const { return _c; }
    private:
        T _a, _b, _c;
};

#endif

tests.cpp(无法编辑 tests.cpp 文件,教授创建了这个文件并锁定了编辑)

#include <iostream>

#include "sorter.h"

template <typename T>
void test_sort(std::istream& in, std::ostream& out)
{
    T a, b, c;
    in >> a >> b >> c;
    sorter<T> s {a, b, c};
    out << s.a() << ' ' << s.b() << ' ' << s.c();
}

int main(int, char* argv[])
{
    using namespace std;
    if (argv[2] == "int"s) {
        test_sort<int>(cin, cout);
    } else if (argv[2] == "char"s) {
        test_sort<char>(cin, cout);
    } else if (argv[2] == "string"s) {
        test_sort<std::string>(cin, cout);
    } else {
        cerr << "ungecognized test type.\n";
        return 1;
    }
    return 0;
}

错误:

./tests.cpp:17:20: error: unable to find string literal operator 'operator""s' with 'const char [4]', 'long unsigned int' arguments
     if (argv[2] == "int"s) {
./tests.cpp:19:27: error: unable to find string literal operator 'operator""s' with 'const char [5]', 'long unsigned int' arguments
     } else if (argv[2] == "char"s) {
./tests.cpp:21:27: error: unable to find string literal operator 'operator""s' with 'const char [7]', 'long unsigned int' arguments
     } else if (argv[2] == "string"s) {

问题:我是否应该更改 sorter.h 以允许代码正常工作,而不会再次出现错误?
-抱歉,没有真正解释我的问题是什么。

最佳答案

您打算与 s 一起使用的字符串文字运算符在字符串文字之后,例如这里:

if (argv[2] == "int"s)

std::literals::string_literals 中定义.它需要导入到当前上下文中,以便通过非限定名称查找找到它。

通常这是通过 using namespace std::string_literals; 完成的在使用运算符的适当范围内。以 using namespace std; 为例在你的代码中,它应该放在 main 中:

int main(int, char* argv[])
{
    using namespace std;
    using namespace std::string_literals;

...

您的问题表明您不应该更改 main .在那种情况下,无论是谁给您分配的,这都是一个明显的错误。

如果你真的想让这个在这个特定的实例中工作,只修改 sorter.h , 那么你也可以加上using namespace std::string_literals;#include <utility> 之后.然而,放置 using namespace 被认为是不好的风格。头文件中的语句,因为它以不受控制的方式将名称引入所有使用头文件的翻译单元的全局命名空间,不应这样做。

这里的错误是你的教授犯了一个简单的错误,他们很容易修复。

关于c++ - 将 C++ 类更改为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59061263/

相关文章:

c++ - const int*、const int * const 和 int const * 之间有什么区别?

c++ - 如何构造一个 std::string 具有可变数量的空格?

python - 如何捕获使用 python subprocess.checkout() 调用调用的 C++ 程序中发生的异常?

python - 如何将类对象的所有方法的结果作为一个列表返回?

ruby-on-rails - 更改默认的多态类型列名

templates - Play 框架 Scala 模板中的“匹配”导致编译错误

c++ - 在 C++ 中实现 "tail -f"

c++ - 模板的 typedef 是否保留静态初始化顺序?

c++ - 类模板的 constexpr 运算符重载

javascript - 如何使用 getElementsByClassName 选择具有类的元素并单击它们?