[C++]関数が存在しないときに他の関数を実行させる方法
Posted: 2018年5月19日(土) 00:35
こんばんは。
C++で関数が存在するしているときはその関数を実行し、存在しないときは他の関数を実行できるようにするという処理を考えています。現在は以下のようなコードを用いて処理を分岐させています。
実際はこれでもいいのですが、これは逐一グローバル領域でcall_definded_functionを書く必要が出てきてしまします。
ライブラリ開発の都合上、なるべく似たような名前のクラスの量産は避けたいものです。なので、目標としてはこのマクロの多用による似たような名前のクラスの量産の対策、もしくは上記コードの修正案をだしていただけるとありがたいです。
開発環境はwindows8.1でvisual studio 2015を使っています。
C++で関数が存在するしているときはその関数を実行し、存在しないときは他の関数を実行できるようにするという処理を考えています。現在は以下のようなコードを用いて処理を分岐させています。
#include <iostream>
#include <type_traits>
//テスト関数
//void function1() { std::cout << "check function1." << std::endl; }
void function2() { std::cout << "check function2." << std::endl; }
//Function1が存在するならばそれを実行し、存在しないならばFunction2を実行
#define call_definded_function(Name, Function1, Function2)\
struct call_definded_function_##Name {\
template <class T>\
static auto tester(T) -> decltype(static_cast<decltype(Function1)*>(&Function1), std::true_type()) {}\
static std::false_type tester(...) {}\
template <bool flag = decltype(tester(nullptr))::value>\
struct call_struct {\
template <class... Args>\
static auto __call_function(Args... args) {\
return Function1(std::forward<Args>(args)...);\
}\
};\
template <>\
struct call_struct<false> {\
template <class... Args>\
static auto __call_function(Args... args) {\
return Function2(std::forward<Args>(args)...);\
}\
};\
template <class... Args>\
static auto call_function(Args... args) {\
return call_struct<>::__call_function(std::forward<Args>(args)...);\
}\
}
call_definded_function(test, function1, function2);
int main() {
//function2が実行される
call_definded_function_test::call_function();
return 0;
}
ライブラリ開発の都合上、なるべく似たような名前のクラスの量産は避けたいものです。なので、目標としてはこのマクロの多用による似たような名前のクラスの量産の対策、もしくは上記コードの修正案をだしていただけるとありがたいです。
開発環境はwindows8.1でvisual studio 2015を使っています。