Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method template specialization by return type

I have a class with template method that the parameter defines the return type. The default constructor for everything else is ok, but for bool I would like the method to return true. I am trying to specialize it as the following code, but this does not compile.

class Foo {
    template <class T>
    T method() {
        ...
        return T();
    }

    template<>
    bool method() {
       ...
       return true;
    }

};

How I can achieve this?

like image 842
gsf Avatar asked May 23 '26 18:05

gsf


2 Answers

You cannot specialize inside a class scope. According to the C++ standard,

14.7.3/2 An explicit specialization shall be declared in a namespace enclosing the specialized template.

Therefore you should specialize the template member function at namespace scope,

template<> // this should be outside the primary template class definition
bool Foo::method() {
    return true;
}
like image 81
vsoftco Avatar answered May 25 '26 08:05

vsoftco


You can use SFINAE to achieve the desired effect, which technically turns the "specialization" (which is not possible as the other answer explained) into an overload:

template <class T>
typename std::enable_if<
    ! std::is_same< T, bool >::value,
    T
>::type
method() {
    ...
    return T();
}

template <class T>
typename std::enable_if<
    std::is_same< T, bool >::value,
    T
>::type
method() {
    ...
    return true;
}

The above is C++11, with C++14 you can even use std::enable_if_t to make it shorter.

Live example

like image 21
Daniel Frey Avatar answered May 25 '26 07:05

Daniel Frey