Home template specialization compiler error
Reply: 1

template specialization compiler error

user1701840
1#
user1701840 Published in 2018-02-12 02:36:24Z

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>.

songyuanyao
2#
songyuanyao Reply to 2018-02-12 03:15:48Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298178 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO