是否有方法为模板参数指定所需的定义

Is there a way to specify a required definition for template arguments?

本文关键字:定义 参数 有方法 是否      更新时间:2023-10-16

是否允许我编写以下语法:

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()常量

如果你写一些类似的东西

template<typename T>
class MyClass {
    void foo() {
        T t;
        SDL_Rect r = t.getRect();
    }
};

如果CCD_ 6不提供CCD_。


如果你想得到更好的编译器错误消息,你可以使用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();
    }
};

编译器已经回答了您的问题:不,这是不允许的。

无论如何,您并没有在那里声明模板。看起来您正试图声明一个模板类,但语法完全错误。

最有可能的是,你只需要花一些时间学习模板,即像这样的网站http://www.tutorialspoint.com/cplusplus/cpp_templates.htm或者一本好书。

你说:

这是为了确保模板类将具有SDL_Rect getRect() const

你在错误的地方使用了一些语法元素来实现这一点。

您要查找的代码是:

template <class T> class MyClass
{
   public :
      SDL_Rect getRect() const;
};