Pergunta

Suppose we have template class

template <typename T>
class MyTem{
public:
    bool is_T_Pointer(){
        <...>
    }
};
class Cls : MyTem<Cls>{
    <...>
};
int main(void){
    Cls* classOnHeap = new Cls(); /* T is pointer */
    Cls classOnStack; /* T is not pointer */
    <...>
}

I know this is a bad example but if someone could help me find out if T is pointer from template class that would be great.

Remember we have inheritance with template of same class as base class.

Doesn't have to be complete implementation, a vague technique will be enough

Foi útil?

Solução

If the compiler supports C++11 use std::is_pointer:

#include <iostream>
#include <type_traits>

template <typename T>
class MyTem
{
public:
    static const bool IS_POINTER = std::is_pointer<T>::value;
};

int main()
{
    std::cout << MyTem<char*>::IS_POINTER << "\n";
    std::cout << MyTem<char>::IS_POINTER << "\n";
    return 0;
}

See demo http://ideone.com/Mo394 .

Outras dicas

You should employ partial specialization here:

template<class T>
class A
{
public:
    A() {}
};

template<class T>
class A<T*>
{
public:
    A(int) {}
};

Then the following will not compile, because compiler is forced to choose pointer version of template and there is no default constructor:

A<char*> a;

this does compile:

A<char> a;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top