1

テンプレートの使用に関する私の知識は非常に浅いため、この質問をどのように提起すればよいか正確にはわかりませんが、ここでは何もありません。

すべての数値に関数テンプレートを提供したいクラスがあり、この関数テンプレートは、次のような std::string を期待する非テンプレート バージョンを呼び出します。

template< class T > void
add_to_header( const std::string &key, const T &val )
{
    add_to_header( key, std::to_string( val ) );
}

virtual void
add_to_header( const header& header );

virtual void
add_to_header( const std::string &key, const std::string &val );

このコードはきれいにコンパイルされますが、 const char []で呼び出しを行う機能が失われます。

instance.add_to_header( "Example1", 4 ); // successful
instance.add_to_header( "Example2", std::string( "str val" ) ); // successful
instance.add_to_header( "Example3", "Not fun" ); // error - none of the 9 overloads could convert all the argument types

この問題を解決する慣用的な方法は何ですか?

4

2 に答える 2

0

なぜそのためにテンプレートを使用したいのですか? add_to_header 関数を単純にオーバーロードできます...

于 2013-05-16T15:43:01.900 に答える