2

バックグラウンド

boost::variant複数のタイプを格納するために使用する永続性の一般的なコードがいくつかあります。値を出力している間、デフォルトの場合は何もしないコンバーター関数を作成する必要がprotected_backslash_nありましたが、同じ値を返します。

テンプレートパラメータがstd::stringIである特殊なケースでは、それboost::regex_replace()を検索して。\nに置き換え\\nます。

質問

コードは正常に機能しますが、値による戻り値があるため、一般的なケースで余分なコピーを取り除くことができれば便利です

std::string専用バージョンを正常に動作させながらこれを行う方法はありますか?

戻り値をに変更してみましたT const&が、専用バージョンが一致しません。

エラー

GetPipedValues.hpp:15:21: error: template-id ‘protect_backslash_n<std::string>’ for ‘std::string pitbull::protect_backslash_n(const string&)’ does not match any template declaration

コード

template<typename T>
inline T protect_backslash_n( T const& orig )
{
    return orig;  // BAD: extra copy - how do I get rid of this?
}

template<>
inline std::string protect_backslash_n<std::string>( std::string const& orig )
{
    boost::regex expr("(\\n)");
    std::string  fmt("(\\\\n)");
    return boost::regex_replace(
        orig, expr, fmt, boost::match_default | boost::format_all
    );
}
4

2 に答える 2

4

テンプレートにしないでください。ただのオーバーロードです。パラメータが一致する場合、コンパイラはテンプレートのインスタンス化ではなくその関数を選択します。

std::string protect_backslash_n( std::string const& orig);
于 2013-02-13T10:01:19.900 に答える
0

それは単純なはずです:

  template <typename T>
  T const& protect_backslash_n(T const& orig)
  { 
    return orig; 
  }

そして、std::stringあなたがそれを持っていたバージョン。非定数参照を取得するなど、追加のオーバーロードが必要になる場合があります。C ++ 11では、その関数はstd::forward<T>デフォルトの場合を模倣する必要があります。

于 2013-02-13T09:59:36.933 に答える