简体   繁体   中英

How should one overload functions with const/non-const parameters?

I have the following code:

// 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)
{...}

The problem is that this test case:

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

ends up calling the templated version of foo . Obviously, I can just add a few more overloads with various mixes of non- const parameters, but I want to know: is there's a better way to overload foo such that it is specialized on all const and non- const pairings of strings? One that doesn't require me to hope I haven't missed some permutation of argument types?

Thanks to Mooing Duck's suggestion, this is my solution:

// 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)
{...}

If I understand your goals properly you could do this

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

This has the advantage of you handling every instance you want explicitly while generating a compilation error if you missed one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM