Hiện thực method trong template class C++

Tôi gặp vấn đề khi cố gắng hiện thực method doSomething() trong class Outer theo cách này:

template <class T>
class Outer
{
public:
	class Inter
	{
	public:
		Inter() {}
	};
	Outer() {}
	Inter doSomething();
};

template <class T>
Outer<T>::Inter Outer<T>::doSomething()
{
	std::cout << "Right!" << endl;
	return Inter();
}

Nếu là 1 class bình thường thì cách này sẽ ổn.
Mong mọi người giúp tôi tìm ra giải pháp.

1 Like

Quan trọng: Vấn đề bạn gặp phải là gì?

6 Likes

Nếu tôi hiện thực đúng như code mẫu thì sẽ bị lỗi, dường như compiler không hiểu được cách viết của tôi, bạn có giải pháp nào không? Tôi muốn đưa code hiện thực method sang file khác.

Không biết bạn có đọc qua “thông báo lỗi” không?
error: need 'typename' before 'Outer<T>::Inter' because 'Outer<T>' is a dependent scope
Nó thông báo rõ ràng tại sao lại lỗi, và có luôn cả cách sửa lỗi luôn rồi mà?
Link tham khảo: https://gcc.godbolt.org/z/o1ro8K

5 Likes

https://en.cppreference.com/w/cpp/language/dependent_name

In a declaration or a definition of a template, including alias template, a name that is not a member of the current instantiation and is dependent on a template parameter is not considered to be a type unless the keyword typename is used or unless it was already established as a type name, e.g. with a typedef declaration or by being used to name a base class.

6 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?