Curious about parameter type inference of c++ function template

Asked 2 years ago, Updated 2 years ago, 182 views

#include <type_traits>

class A{};

template< typename T > struct is_allowed 
{ 
    enum { value = false };
};

template<>  struct is_allowed<A>
{ 
    enum { value = true };  
};


template< typename T >
void f( std::enable_if_t< is_allowed<T>::value , T >* Parent )
{

}

int main()
{
    A a;
    f( &a );

    return 0;
}


There's a simple function template. Why can't we say that function f doesn't make type inference for class A? The development environment is VC2017.

Error message: error C2783: 'voidf(enable_if<_Test,T>:type *)': could not delete template argument for 'T'

c++ template

2022-09-22 19:03

1 Answers

http://en.cppreference.com/w/cpp/language/template_argument_deduction#Non-deduced_contexts

contains the following information:

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

In your question, P is std::enable_if<is_allowed<T>::value, T>:type*.

In some cases, :: may be used to access the internal name using :: such as ::type with In the following cases.

In other words, because you used ::type in P, it is included in the case of non-deduced contexts, which is the error you mentioned because of the rule that you do not make type inference.

std::enable_if<is_allowed<T>::value, T>:type* is not an inference, so in order to replace it with A* you need to modify it so that T can be inferred.

Therefore, T can be changed as below to make it simple to infer.

template< typename T >
void f( T* Parent, std::enable_if_t< is_allowed<T>::value , T >* = 0 )
{
}


2022-09-22 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.