実際の文字列を数値に変換します

これは、の練習のstd :: enable_if、STD :: is_sameとstd ::崩壊の一例です。
こじつけの変換に使用される一般的な文字列は、実際には、この専門的な関数テンプレートで、より適切かもしれません。
「C ++プログラミング言語」メタプログラミングスピークSTDを参照のstd :: enable_ifを使用する場合のよう:: enable_ifより適切な例があります。
 
 書式#include <文字列>
書式#include <type_traits>
 
 
 
 名前空間の詳細{
    テンプレート<クラスT、クラスの有効化=無効>
    構造体ConvertToNumeric
    {
        T演算子()(constのはstd ::文字列&STR)のconst
        {
            リターンははstd :: STOI(STR);
        }
    }。
 
    //特殊なケース
 
    テンプレート<ブールB、クラスT>
    使用T_enable_if_t =型名のstd :: enable_if <B、T> ::タイプ。
 
    テンプレート<クラスU、クラスT>
    T_same_enable_t使用= T_enable_if_t <STD :: is_same <T、U> ::値、T>。
 
    テンプレート<クラスT>
    構造体ConvertToNumeric <T、T_same_enable_t <長い、T >>
    {
        長いオペレータ()(constのはstd ::文字列&STR)のconst
        {
            返すのstd :: STOL(STR);
        }
    }。
 
    テンプレート<クラスT>
    構造体ConvertToNumeric <T、T_same_enable_t <unsigned long型、T >>
    {
        符号なしlong演算子()(constのはstd ::文字列&STR)のconst
        {
            返すのstd :: stoul(STR);
        }
    }。
 
    テンプレート<型名T>
    構造体ConvertToNumeric <T、T_same_enable_t <長い長い、T >>
    {
        長い長いオペレータ()(constのはstd ::文字列&STR)のconst
        {
            リターンのstd ::ストール(STR);
        }
    }。
 
    テンプレート<型名T>
    構造体ConvertToNumeric <T、T_same_enable_t <符号なしの長い長い、T >>
    {
        符号なしの長い長いオペレータ()(constのはstd ::文字列&STR)のconst
        {
            リターンははstd :: stoull(STR);
        }
    }。
 
    テンプレート<型名T>
    構造体ConvertToNumeric <T、T_same_enable_t <フロート、T >>
    {
        フロート演算子()(constのはstd ::文字列&STR)のconst
        {
            返すのstd :: STOF(STR);
        }
    }。
 
    テンプレート<型名T>
    構造体ConvertToNumeric <T、T_same_enable_t <ダブル、T >>
    {
        ダブル演算子()(constのはstd ::文字列&STR)のconst
        {
            std :: STOD(STR)を返します。
        }
    }。
 
    テンプレート<型名T>
    構造体ConvertToNumeric <T、T_same_enable_t <long double型、T >>
    {
        長いダブル演算子()(constのはstd ::文字列&STR)のconst
        {
            std :: stold(STR)を返します。
        }
    }。
}
 
 
//この複雑な方法は、また、関数テンプレートの特殊化を使用します
/ ***************************************** /
/ *
テンプレート<型名T>
インラインT str_to_numeric(のconstのstd ::文字列&STR)
{
    リターンははstd :: STOI(STR);
}
 
テンプレート<>
<ロング>(定数のstd ::文字列&strの)インライン長いstr_to_numeric
{
    返すのstd :: STOL(STR);
}
...
* /
 
テンプレート<型名T>
インラインT str_to_numeric(のconstのstd ::文字列&STR)
{
    使用T_decay_t =型名のstd ::崩壊<T> ::タイプ。
    戻り詳細:: ConvertToNumeric <T_decay_t、T_decay_t>()(STR);
}

おすすめ

転載: www.cnblogs.com/water-bear/p/11940461.html