应该如何使用const/non-const参数进行重载?

mos*_*ald 6 c++ overloading c++11

我有以下代码:

// 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)
{...}
Run Code Online (Sandbox Code Playgroud)

问题是这个测试用例:

char test[] = "test";
foo("test", test);
Run Code Online (Sandbox Code Playgroud)

最终调用模板化的版本foo.显然,我可以添加一些带有各种非const参数混合的重载,但我想知道:是否有更好的方法来重载foo,以便它专注于所有const和非const配对的字符串?一个不要求我希望我没有错过一些参数类型的排列?

mos*_*ald 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)
{...}
Run Code Online (Sandbox Code Playgroud)

  • 您只能使用“std::forward”[通用引用](http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers)。 (2认同)