Error C2784: Failed to output template argument

Continued struggle with patterns. In this example, despite being copied directly from the book, I get the following error message:Error 2 error C2784: 'IsClassT<T>::One IsClassT<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'.

This is an example from the Templates - Complete Guide book . (I work with Visual Studio 2010 RC).

  template<typename T> 
    class IsClassT { 
      private: 
        typedef char One; 
        typedef struct { char a[2]; } Two; 
        template<typename C> static One test(int C::*); 
        template<typename C> static Two test(…); 
      public: 
        enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; 
        enum { No = !Yes }; 
    }; 

class MyClass { 
}; 

struct MyStruct { 
}; 

union MyUnion { 
}; 

void myfunc() 
{ 
} 

enum E {e1} e; 

// check by passing type as template argument 
template <typename T> 
void check() 
{ 
    if (IsClassT<T>::Yes) { 
        std::cout << " IsClassT " << std::endl; 
    } 
    else { 
        std::cout << " !IsClassT " << std::endl; 
    } 
} 

// check by passing type as function call argument 
template <typename T> 
void checkT (T) 
{ 
    check<T>(); 
} 

int main() 
{ 
    /*std::cout << "int: "; 
    check<int>(); */

    std::cout << "MyClass: "; 
    check<MyClass>(); 
}

And although I know exactly what is happening in this example, I cannot fix this error.
Thanks for the help.

+3
source share
3 answers

My compiler (MSVC2008TS) loves it if you do not fully qualify the expression test:

enum { Yes = sizeof(test<T>(0)) == 1 }; 

But is this even a legal code?

+5
source

Should this line not

    enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; 

will be

    enum { Yes = sizeof(IsClassT<T>::template test<T>(0)) == 1 }; 

instead? `

( , sizeof(IsClassT<T>::template test<T>(0)) == sizeof(One).)

+3

Not quite the answer to this question, but a different approach to your problem. It’s easier for me to run SFINAE tests by specialization, and not by the functions defined in this template:

// used to pass a type tested with SFINAE
template<typename T> struct tovoid { typedef void type; };

Using this to pass a type that might be invalid:

template<typename T, typename U = void> 
struct is_class {
  static bool const value = false;
};

// if "int T::*" is a valid type, this specialization is used
template<typename T>
struct is_class<T, typename tovoid<int T::*>::type> {
  static bool const value = true;
};

Thus, it is much shorter and noise with sizeofand everything is not done.

+1
source

Source: https://habr.com/ru/post/1737152/


All Articles