Home > front end >  type deduction guide on variadic template function
type deduction guide on variadic template function

Time:08-24

I found some solutions for type deduction guides for variadic classes but not for functions like I intent to use.

First, this works as expected:

template<typename... T>
void print(T&&... args) {
    ((std::cout << args),...);   
}

int main() {
    print("Hello ", "World! ", "The answer is ", 42);   
}

gives:

Hello World! The answer is 42

As 2nd, I want to constraint the template argument count using C 20 concept as:

constexpr auto MAX_ARGS = 4;

template<typename... T> concept ArgsT = requires(T... args) {
    // count must be even
    requires (sizeof...(T)) % 2 == 0;
    // the count is limited by arg count size
    requires (sizeof...(T)) / (2*MAX_ARGS 1) == 0;
};

template<ArgsT... T>
void print(T&&... args) {
    ((std::cout << args),...);   
}

and the problem starts with constraints not satisfied ...

So, next a type deduction guide shall help here, and here I am:

template<ArgsT... T>
void print(T&&... args) {
    ((std::cout << args),...);   
}

template<typename... T>
auto print(T&&... args) -> template<typename T> auto print<T...>(T&&...);

int main() {
    print("Hello ", "World! ", "The answer is ", 42);   
}

gives error error: expected a type, see godbolt.org Clang gives some hints, but finally I wasn't able to write the deduction guide with this. How does it look so that the constraint function print(...) compiles, or even rejects due to violated concepts? It must compile on the Big 3 compiler.

CodePudding user response:

template<ArgsT... T> is incorrect, ArgsT only applies to a single type, that is, it only checks whether ArgsT<T> is satisfied, so it will never be satisfied. You should use requires-clause for this

template<class... T>
  requires (sizeof...(T) % 2 == 0) && 
           ((sizeof...(T)) / (2*MAX_ARGS 1) == 0)
void print(T&&... args) {
  ((std::cout << args),...);   
}
  • Related