user1701840
user1701840

Reputation: 1112

template specialization compiler error

I have a main.cpp and a header file called bar.h This is the main.cpp. My goal is to have the program print out "bar":

#include "bar.h"

struct Raw{
};

template<typename Obj>
struct IsBar{
    static const bool value = false;
};

template<typename Obj, bool>
struct function{
    static void callbar(Obj obj){ 
        obj.bar();
    }; 
};

template<typename Obj>
struct function<Obj, false>{
    static void callbar(Obj obj){ 
        std::cout<< "no bar()" << std::endl;
    }; 
};

int main()
{
    typedef Bar<Raw> Obj;
    Obj obj;

    function<Obj, IsBar<Obj>::value> f;
    f.callbar(obj); 

    return 0;
}

For the bar.h:

template<typename T>
struct Bar{
    void bar()
    {
        std::cout<< "bar" << std::endl;
    };
};

template<>
struct IsBar<Bar>{ // I know this wouldn't work, but how do I do something like Bar<Raw> instead of just Bar?
    static const bool value = true;
};

Compiler gave me this error: error: 'IsBar' is not a class template. Previously I tried to have the content of bar.h inside the main.cpp, and everything works fine, because Raw is known when I declared the IsBar<> specialization using Bar<Raw>.

Upvotes: 2

Views: 38

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

You want partial specialization, e.g.

template<typename T>
struct IsBar<Bar<T>> {
    static const bool value = true;
};

That means for all the instantiations of Bar<T>, IsBar<Bar<T>>::value is true.

Note that the primary template should be declared before the specialization; I think you should move the primary template definition of IsBar from main.cpp to bar.h.

LIVE

Upvotes: 2

Related Questions