How can I overload functions with constant / non-constant 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 with a call to the templated version of foo . Obviously, I can add a few more overloads with different mixes of parameters not const , but I want to know: is there a better way to overload foo so that it specializes in all const const pairs of strings? One that does not require me to hope that I have not missed any kind of permutation of argument types?

+6
source share
2 answers

Thanks to the Mooing Duck 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) {...} 
+3
source

If I understand your goals correctly, you can do it

 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 that you process every instance that you want explicitly, generating a compilation error if you missed it.

0
source

All Articles