こんばんは。テンプレート関数の特殊化についてわからない部分があるので、教えてください。
テンプレート関数の特殊化の例として、以下のようなものが書けますが、
c++
1#include <iostream> 2 3class Hoge 4{ 5public: 6 template <typename T> 7 void TemplateFunction() 8 { 9 std::cout << "TemplateFunction() :: normal version!" << '\n'; 10 } 11}; 12 13/** 14 * int,float に対して特殊化 15 */ 16template <> 17void Hoge::TemplateFunction<int>() 18{ 19 std::cout << "TemplateFunction() :: int version!" << '\n'; 20} 21 22template <> 23void Hoge::TemplateFunction<float>() 24{ 25 std::cout << "TemplateFunction() :: float version!" << '\n'; 26} 27 28 29/** 30 * main() 31 */ 32 33int main(int argc, char const *argv[]) { 34 35 Hoge hoge; 36 std::cout << "Hoge class test" << '\n'; 37 hoge.TemplateFunction<double>(); 38 hoge.TemplateFunction<int>(); 39 hoge.TemplateFunction<float>(); 40 41 return 0; 42} 43
< 実行結果 >
Hoge class test TemplateFunction() :: normal version! TemplateFunction() :: int version! TemplateFunction() :: float version!
この特殊化は1つの型に対して1つの特殊化された関数というようになっています。僕のやりたいのはこれではなく、複数種類の型に対して特殊化された関数を1つ作るということがしたいです。例えば、
c++
1class Hoge 2{ 3public: 4 template <typename T> 5 void TemplateFunction() 6 { 7 std::cout << "TemplateFunction() :: normal version!" << '\n'; 8 } 9}; 10 11/** 12 * int,float に対して特殊化 13 */ 14template <> 15void Hoge::TemplateFunction<int>() 16{ 17 std::cout << "TemplateFunction() :: int version!" << '\n'; 18} 19 20template <> 21void Hoge::TemplateFunction<float>() 22{ 23 std::cout << "TemplateFunction() :: float version!" << '\n'; 24} 25 26/** 27 * typename T = double または char の時はこっちが呼ばれる 28 */ 29template <> 30void Hoge::TemplateFunction<double or char>() 31{ 32 std::cout << "TemplateFunction() :: double or char version!" << '\n'; 33}
このように、テンプレート引数がdoubleまたはcharのときは1番下の関数が呼ばれるようにしたいのです。double、char型それぞれに対して全く同じ中身のTemplateFunction<double>()
とTemplateFunction<char>()
を定義すれば実現できますが、これだと中身が同じ内容の関数をいくつも書くことになってしまいます。他に方法はないでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/05 15:05
2017/05/05 15:15
2017/05/05 15:48
2017/05/05 18:28
2017/05/05 23:12