0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++でSwiftのプロトコルみたいなインターフェースを作りたい

Last updated at Posted at 2022-07-27

ターゲット

C++がメインだけどSwiftのプロトコルなど便利機能に慣れちゃった人
テンプレート仮想クラスをどう使ったら良いかわからない人

作成例

数字を扱うクラス(Number)と足し算の実装を強要するプロトコル(Addable)を作ってみる

足し算のプロトコル

template <typename T>
class Addable
{
public:
	Addable() noexcept = default;
	virtual ~Addable() noexcept = default;

	virtual T& operator += (const T& r) = 0;
};

数字を扱うクラス

template <typename T>
class Number : public Addable<Number<T>>
{
public:
	Number() noexcept = default;
	Number(T value) : m_Value(value) {}
	~Number() noexcept override = default;

	operator T() const
	{
		return m_Value;
	}
	Number& operator += (const Number& r) override
	{
		m_Value += r.m_Value;
		return *this;
	}

private:
	T m_Value;
};

template <typename T>
Number<T> operator + (const Number<T>& l, const Number<T>& r)
{
	return Number<T>(l) += r;
}

テスト用コード

#include <iostream>

int main()
{
	Number<int> var0{ 1 };
	Number<int> var1{ 5 };

	std::cout << var0 + var1 << std::endl;

	return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?