Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

oop - auto return type for a C++ member function of a template class

For the sake of readability I will simplify my problem into a nice toy example:

Let's say I have a template class Box which can hold a finite collection of objects of a given type (initialised as Box<double, 10>). The class has a member function called expand(n) which should modify the box such that the capacity is higher. Since the 10 is a specification of class instance I believe it is reasonable for the method to return a new object instead (ex. Box<double, 20>, for the function argument n given 20).

I am having problems with a proper signature for the method. What I have is:

template <typename T, const unsigned int size>
Box Box<T, size>::expand(const unsigned int newsize) const {

Naturally, the problem is with the return type... I cannot just add <T, newsize> since the latter is not yet in the scope.

I have been trying to use a trailing return syntax:

template <typename T, const unsigned int size>
auto Box<T, size>::expand(const unsigned int newsize) -> Box<T, newsize> const {

But something is wrong here and I get errors.. How should I modify it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Parameters of template must be decided in compilation time, so you cannot use function arguments, which is decided in run time. You should add the parameter as template argument instead.

template <typename T, const unsigned int size>
struct Box {
    template<const unsigned int newsize>
    Box<T, newsize> expand() const;
};

template <typename T, const unsigned int size>
template <const unsigned int newsize>
Box<T, newsize> Box<T, size>::expand() const {
    return Box<T, newsize>();
}

int main() {
    Box<double, 10> b;
    Box<double, 20> b2 = b.expand<20>();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...