0

I don't know if this is possible, but I would like to understand better how this works.

Can a class implict convertsion operation be used to match a template parameter? This is what I want to do.

#include <iostream>

template<typename T>
struct Value {
};

template<>
struct Value<int> {
    static void printValue(int v) {
        std::cout << v << std::endl;
    }
};

struct Class1 {
    int value;
};

/*
template<>
struct Value<Class1*> {
    static void printValue(Class1* v) {
        std::cout << v->value << std::endl;
    }
};
*/

template<typename X>
struct ClassContainer {
    ClassContainer(X *c) : _c(c) {}
    operator X*() { return _c; }
    X *_c;
};

template<typename X>
struct Value<ClassContainer<X>> {
    static void printValue(ClassContainer<X> v) {
        std::cout << static_cast<X*>(v)->value << std::endl;
    }
};

template<typename X>
void doPrintValue(X v)
{
    Value<X>::printValue(v);
}

int main(int argc, char *argv[])
{
    doPrintValue(10);

    Class1 *c = new Class1{ 20 };
    //doPrintValue(c); // error C2039: 'printValue': is not a member of 'Value<X>'

    ClassContainer<Class1> cc(c);
    doPrintValue(cc);

    std::cout << "PRESS ANY KEY TO CONTINUE";
    std::cin.ignore();
}

ClassContainer has an implict conversion to X*. Is it possible to match ClassContainer passing only X*?

Rangel Reale
  • 698
  • 6
  • 7

1 Answers1

1

If you want the template class for pointers to behave like the template class for something else, just inherit:

template<typename T>
struct Value<T*> : Value<ClassContainer<T>> {};

It will inherit the public printValue function, which accepts a parameter that can be constructed from T*, and everything will be implicitly converted as expected.

See it all live here.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458