Specialization of the Variadic template with reference to a constant

How to specialize a function of a variational template that has a const reference for an argument?

Example:

template<typename T, typename... Args> T foo(Args... args) = delete; template<> int foo(int a, const char* str, const Test& t) { .... } // Fails to compile //template<> int foo(int a, const char* str, Test ) { .... } // Ok int main() { auto i = foo<int>(10, "test string!", t); return 0; } 

When calling the foo function with the declared argument const Test& compiler does not see the specialized function and backups for the remote function:

  error: use of deleted function 'T foo(Args ...) [with T = int; Args = {int, const char*, Test}]' auto i = foo<int>(10, "test string!", t); 




The above code compiles if I remove the const link from the argument. What am I doing wrong?

The code can be found here.

+8
c ++ template-specialization variadic-templates
source share
2 answers

The automatic template output is not smart enough to suggest that you want to set the last template parameter const Test& instead of Test . More accurate type inference always removes cv classifiers from the type.

Here you create a new explicit template:

 auto i = foo<int, int, const char *, const Test&>(10, "test string!", t); 
+3
source share

This is because the template arguments that the primary template prints for your call are int , const char* and Test , not const Test& . This means that your specialization is not used, because the template arguments do not match the parameters.

Your easiest option is to provide a separate overload, not a specialization:

 template <typename T> T foo(int a, const char* str, const Test& t) { /*...*/; } 

Live demo

+7
source share

All Articles