我可以写这个语法吗:
template <class T{public :SDL_Rect getRect() const; }>
这是为了确保模板参数将具有 SDL_Rect getRect() const
但是我得到了error: unexpected Type "T"
。如果我在语法上犯了错误或者根本不允许这样做,有什么建议吗?
我可以写这个语法吗:
template <class T{public :SDL_Rect getRect() const; }>
这是为了确保模板参数将具有 SDL_Rect getRect() const
但是我得到了error: unexpected Type "T"
。如果我在语法上犯了错误或者根本不允许这样做,有什么建议吗?
有概念:
template<class T>
requires requires(const T t) {
{ t.getRect() } -> SDL_Rect;
}
class Meow { };
这将检查t.getRect()
隐式转换为SDL_Rect
. 要检查完全匹配,
template<class T, class U> concept bool Same = std::is_same_v<T, U>;
template<class T>
requires requires(const T t) {
{ t.getRect() } -> Same<SDL_Rect>;
}
class Meow { };
这是为了确保模板类将具有
SDL_Rect getRect()
const
如果你写类似
template<typename T>
class MyClass {
void foo() {
T t;
SDL_Rect r = t.getRect();
}
};
T
如果不提供该SDL_Rect getRect()
功能,编译器就会抱怨。
如果您想获得更好的编译器错误消息,可以使用 a static_assert
,例如:
template<typename T>
class MyClass {
static_assert(std::is_member_function_pointer<decltype(&T::getRect)>::value,
"T must implement the SDL_Rect getRect() const function");
void foo() {
T t;
SDL_Rect r = t.getRect();
}
};
你说:
这是为了确保模板类将具有
SDL_Rect getRect() const
你在错误的地方有一些句法元素来实现这一点。
您正在寻找的代码是:
template <class T> class MyClass
{
public :
SDL_Rect getRect() const;
};
编译器已经回答了你的问题:不,这是不允许的。
无论如何,您都没有在那里声明模板。看起来您正试图声明一个模板类,但语法全错了。
很可能,您只需要花一些时间学习模板,例如http://www.tutorialspoint.com/cplusplus/cpp_templates.htm之类的网站或一本好书。