C++11: Template Function Specialization for Integer Types

后端 未结 5 1510
挽巷
挽巷 2020-12-04 19:52

Suppose I have a template function:

template
void f(T t)
{
    ...
}

and I want to write a specialization for all primiti

5条回答
  •  借酒劲吻你
    2020-12-04 20:07

    You can use a helper template that you can specialize like this:

    #include 
    #include 
    #include 
    
    template ::value>
    struct Foo {
            static void bar(const T& t) { std::cout << "generic: " << t << "\n"; }
    };
    template 
    struct Foo {
            static void bar(const T& t) { std::cout << "integral: " << t << "\n"; }
    };
    
    template 
    static void bar(const T& t) {
            return Foo::bar(t);
    }
    
    int main() {
            std::string s = "string";
            bar(s);
            int i = 42;
            bar(i);
            return 0;
    }
    

    output:

    generic: string
    integral: 42
    

提交回复
热议问题