dani
dani

Reputation: 3887

How can I influence the return type of a template class method based on some template argument?

A template class should have a method who's return type is based on a template argument. In this example, how can I make the function return int (a copy) for K=0 and int& (ref) for K=1?

template<typename T, int K>
class someclass
{
public:
    someclass() : member(3) { }
    T giveback() { return member; } // if K=0 should return by T, else return by T&
private:
    T member;
};

int main()
{
    someclass<int,0> x;
    x.giveback();
}

Upvotes: 2

Views: 55

Answers (1)

Brian Bi
Brian Bi

Reputation: 119174

You can do this:

typename std::conditional<K, T&, T>::type giveback() { return member; }

If K is 0 then the type will be T, otherwise it will be T&.

There isn't really any such thing as "without template specialization" though, since std::conditional is implemented using template specialization. Using std::conditional just helps you localize the template specialization and not have to duplicate large parts of your entire class.

Upvotes: 6

Related Questions