同じように使用される一連の関数に統一されたインターフェイスを提供するにはどうすればよいでしょうか? 説明のために、与えられたライブラリ関数のセットを見てください:
/* existing library functions */
/* the signatures are different: some return int, some float */
/* set of input related functions */
int getInputValue() { return 42; }
size_t getInputSize() { return 1; }
/* set of output related functions */
int getOutputValue() { return 21; }
size_t getOutputSize() { return 1; }
/* set of parameter related functions */
float getParameterValue() { return 3.14; }
size_t getParameterSize() { return 1; }
同じように使用されると仮定します。
if (getSize() > 0) {
T value = getValue()
getSize()
A) 提供する良い方法は何getValue()
ですか?
最初に、テンプレート メソッド パターンが必要だと思いましたが、適用できませんでした。これは、テンプレート メソッド パターンのワーカーとは対照的に、関数のシグネチャが異なるためです。
だから私が代わりにしたこと:
/* I want to provide a uniform interface */
/* the specific part of inputs, outputs and parameters is in the traits */
struct input_traits {
typedef int value_type;
static int getValue() { return getInputValue(); }
static size_t getSize() { return getInputSize(); }
};
struct output_traits {
typedef int value_type;
static int getValue() { return getOutputValue(); }
static size_t getSize() { return getOutputSize(); }
};
struct parameter_traits {
typedef float value_type;
static float getValue() { return getParameterValue(); }
static size_t getSize() { return getParameterSize(); }
};
/* the common part (they are used in the same way) is in the Helper */
template<typename traits>
class CommonUsage {
public:
void use()
{
if (traits::getSize() > 0) {
typename traits::value_type value = traits::getValue();
}
}
};
int main()
{
CommonUsage<input_traits>().use();
CommonUsage<output_traits>().use();
CommonUsage<parameter_traits>().use();
}
B) これは良いアプローチですか?