6

次のコードがあります。

// string specializations
void foo(const char *a, const char *b);
void foo(const char *a, const std::string &b);
void foo(const std::string &a, const char *b);
void foo(const std::string &a, const std::string &b);

// generic implementation
template<typename TA, typename TB>
void foo(TA a, TA b)
{...}

問題は、このテスト ケース:

char test[] = "test";
foo("test", test);

のテンプレート化されたバージョンを呼び出すことになりfooます。明らかに、非パラメーターのさまざまな組み合わせでいくつかのオーバーロードを追加することもできconstますが、知りたいのは、文字列のすべておよび非ペアリングにfoo特化するようにオーバーロードするより良い方法はありますか? 引数の型の順列を見逃していないことを期待する必要がないものはありますか?constconst

4

2 に答える 2

3

Mooing Duck の提案のおかげで、これが私の解決策です。

// string specialization
void foo(const std::string &a, const std::string &b);

template<typename TA, typename TB>
typename std::enable_if<
    std::is_constructible<std::string, TA>::value &&
    std::is_constructible<std::string, TB>::value
>::type foo(TA a, TB b)
{
    foo(std::string(std::move(a)), std::string(std::move(b)));
}

// generic implementation
template<typename TA, typename TB>
typename std::enable_if<
    !std::is_constructible<std::string, TA>::value ||
    !std::is_constructible<std::string, TB>::value
>::type foo(TA a, TB b)
{...}
于 2012-11-15T03:53:45.167 に答える
0

私があなたの目標を正しく理解していれば、あなたはこれを行うことができます

template<typename T1,typename T2 >
void foo(T1, T2)
{
     static_assert(sizeof(T1) == 0,"Did not overload all foo's");
}

template<>
void foo<const char *a, const char *b>()
{
    ... Handle this case
}

... ect ect ect

これには、必要なすべてのインスタンスを明示的に処理し、インスタンスを見逃した場合にコンパイルエラーを生成するという利点があります。

于 2012-11-15T03:29:56.597 に答える