我想创建一个通用print(x)函数,它对于不同类型有不同的行为。
到目前为止,我所拥有的适用于所有容器类型,包括我自己编写的容器类型。然而,要么调用了“错误”的函数,要么由于不明确而无法编译。
这是我的代码:
#include <iostream>
#include <concepts>
class Container
{
int x, y, z;
public:
Container(int a, int b, int c) : x(a), y(b), z(c) {}
Container() : x(0), y(0), z(0) {}
std::size_t size() const { return 3; }
const int& operator[] (std::size_t index) const { if(index == 0) return x; else if(index == 1) return y; else return z; }
int& operator[] (std::size_t index) { if(index == 0) return x; else if(index == 1) return y; else …Run Code Online (Sandbox Code Playgroud) 这里必须有更好的方法来做到这一点,对吗?
(format t "Enter your age: ~%")
(defun age-case (age)
(case age
(1 (format t "You belong in Kindergarden~%"))
(2 (format t "You belong in Kindergarden~%"))
(3 (format t "You belong in Kindergarden~%"))
(4 (format t "You belong in Kindergarden~%"))
(5 (format t "You belong in Preschool~%"))
(6 (format t "Elementary school ~%"))
(t (format t "Somewhere else"))))
(defvar *age* (read))
(age-case *age*)
Run Code Online (Sandbox Code Playgroud)
在 Python 中,我会为此使用 case 1..4,在 C++、Java 和 co 中。我可能会使用falltrough switch case,在这种情况下我省略了case 1到3的break。在clisp中是否有一个巧妙的小技巧可以在没有代码重复的情况下做到这一点?